Reputation: 1924
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?
Upvotes: 3
Views: 272
Reputation: 790
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;
Upvotes: 1