2

I have a basic node.js app serving a static index.html that contains a JS app. I have a login route that validates a username/pwd against my mongo database and redirects to '/':

app.post('/login', function(req,res) {
    let inputUser=req.body.username;
    let inputPwd=req.body.password;

    findUser({'username':inputUser},function(data){
        if ((data[0].srnm===inputUser)&&(data[0].psswd===inputPwd))
        {
            res.redirect('/');
        }
        else
        {
            res.writeHead(200);
            res.write(`INVALID USERNAME OR PASSWORD TRY AGAIN OR GO AWAY`);
            res.end();
        }
    });
});

My index.html contains a script.src JS app.

app.get('/', function (req, res) {
    res.sendFile(path.join(__dirname+'/index.html')); 
});

I want to access an IS_LOGGED_IN flag in this script.

How do I pass the script this information? Do I need to do an AJAX request / put it in a header before my redirect somehow? Or is my approach somehow flawed? Sorry if this is blatantly obvious. I'm very new to node (and also need to learn async.js/promises to avoid callback hell). Thanks.

3 Answers 3

3

A good approach is using a Template Engine instead of serving a pure .html file, so:

Managing the Index Route:

  1. Install a Basic Template Engine npm install ejs --save
  2. Use it as Express Template Engine app.set('view engine', 'ejs')
  3. Set the views path app.set('views', path.join(__dirname, 'views'));
  4. Render app.get('/'. (req, res) => res.render('Index', {IS_LOGGED: true });
  5. Index.ejs <script>window.INITIAL_STATE = {IS_LOGGED: <%- IS_LOGGED %>}; </script>

Managing the Login API:

Instead of res.write(200); ...INVALID USERNAME..., respond with a more consistent status code so your client can understand when a login request is done.

app.get('/login', (req, res) => res.status(401).end());

Sign up to request clarification or add additional context in comments.

Comments

0

You can use Ajax script then you should pass a JSON response

res.send({IS_LOGGED_IN: true})

Or past your flag as a flash session using express-flash module (https://www.npmjs.com/package/express-flash)

Example

req.flash('IS_LOGGED_IN', true);

On html page render you get your flag by:

app.get(function(req, res, next){
    return res.render('index.html', {
        IS_LOGGED_IN: req.flash('IS_LOGGED_IN'),
    });
});

Comments

0

If all you want to do is indicate to your on-page script that a user is logged in, the easiest way would be to set a cookie in the log on script.

res.cookie('loggedIn', 'true')

Then access it from within your script.

<script type="text/javascript">
        function setCookie(key, value) {
            var expires = new Date();
            expires.setTime(expires.getTime() + (1 * 24 * 60 * 60 * 1000));
            document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
        }

        function getCookie(key) {
            var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
            return keyValue ? keyValue[2] : null;
        }

    if (getCookie('loggedIn')) {
        document.write('User is logged in')
    }
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.