Jo Colina Jo Colina - 3 months ago 14
Node.js Question

Add an exception to ExpressJS app.use()

I'm working on a NodeJS project, and using Express as my routing framework.

I have a register form in my site, and a login form, both of which send requests to

/users
(
/register
and
/login
respectively). However, I would like to be able to have
/users/:userID
as routes to see profiles of different users, but of course, this routes imply that I have a session_id for every logged in user.

My question is, how can I use
app.use('/users', checkForSessionId)
, without applying it to register and login?

Answer

This is where you need to use middleware

app.js

var users = require('./routes/user');
app.use('/users', users);

./routes/user.js

var express = require('express');
var router = express.Router();
function checkForSessionId(req, res, next){
    //if no valid session
    //    return res.status(401).json("not authorised");
    //else
    next();
}

router.get('/:userId', checkForSessionId, function(req, res){
    //this is a route which requires authentication
})

router.post('/register', function(req, res){
    //authentication is not necessary
})

module.exports = router;