在ExpressJS中添加一个异常app.use()

Add an exception to ExpressJS app.use()

本文关键字:一个 app use 异常 ExpressJS 添加      更新时间:2023-09-26

我正在做一个NodeJS项目,并使用Express作为我的路由框架。

我有一个注册表单在我的网站,和一个登录表单,这两个发送请求到/users (/register/login分别)。但是,我希望能够将/users/:userID作为查看不同用户配置文件的路由,但是当然,这些路由意味着我对每个登录用户都有一个session_id。

我的问题是,我如何使用app.use('/users', checkForSessionId),而不应用它来注册和登录?

这就是您需要使用中间件的地方

app.js

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

。/线路/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;