在nodejs(express)中的router.route()中设置中间件

时间:2016-12-21 13:22:23

标签: node.js express

我想要它做什么。

ExtractTextPlugin

我想检查每条路线的会话。 但由于路由器是以这种方式编写的。

 router.post('/xxxx', authorize , xxxx);

  function authorize(req, res, next)
   {
    if(xxx)
        res.send(500);
    else
     next(); 
   }

那么如何设置一个检查会话的中间件呢?我想让事情变得更通用,并希望让一个授权函数做一件事而不是检查每个请求。任何建议。

2 个答案:

答案 0 :(得分:5)

在定义/包含路由之前定义middlware函数,这将避免您在每个路由中检查有效会话。有关如何执行此操作的示例,请参阅下面的代码。

如果某些路线是公开的,即他们不要求用户拥有有效会话,那么在您使用'之前定义这些路线。你的middlware功能

var app = require("express")();

//This is the middleware function which will be called before any routes get hit which are defined after this point, i.e. in your index.js
app.use(function (req, res, next) {

  var authorised = false;
  //Here you would check for the user being authenticated

  //Unsure how you're actually checking this, so some psuedo code below
  if (authorised) {
    //Stop the user progressing any further
    return res.status(403).send("Unauthorised!");
  }
  else {
    //Carry on with the request chain
    next();
  }
});

//Define/include your controllers

根据您的评论,您有两个关于让此中间件仅影响某些路由的选择,请参阅下面的两个示例。

选项1 - 在中间件之前声明您的特定路由。

app.post("/auth/signup", function (req, res, next) { ... });
app.post("/auth/forgotpassword", function (req, res, next) { ... });

//Any routes defined above this point will not have the middleware executed before they are hit.

app.use(function (req, res, next) {
    //Check for session (See the middlware function above)
    next();
});

//Any routes defined after this point will have the middlware executed before they get hit

//The middlware function will get hit before this is executed
app.get("/someauthorisedrouter", function (req, res, next) { ... });

选项2 在某处定义您的middlware功能并在需要时将其需要

/middleware.js

module.exports = function (req, res, next) {
    //Do your session checking...
    next();
};

现在你可以在任何你想要的地方要求它。

/index.js

var session_check = require("./middleware"),
    router = require("express").Router();

//No need to include the middlware on this function
router.post("/signup", function (req, res, next) {...});

//The session middleware will be invoked before the route logic is executed..
router.get("/someprivatecontent", session_check, function (req, res, next) { ... });


module.exports = router;

希望能让您大致了解如何实现此功能。

答案 1 :(得分:0)

Express路由器具有整洁的use() function,可让您为所有路由定义middlewarerouter.use('/xxxxx', authorize); router.post('/xxxx', 'xxxx');应该可以。