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

sac*_*hal 1 node.js express

我想要它做什么。

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

  function authorize(req, res, next)
   {
    if(xxx)
        res.send(500);
    else
     next(); 
   }
Run Code Online (Sandbox Code Playgroud)

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

router.route('/xxx/xxxx').post(function(req, res) {
    // blah lah here...
    //
});
Run Code Online (Sandbox Code Playgroud)

因此,我该如何设置一个中间件来检查会话,我想使事情变得更通用,并希望有一个单一的授权功能来完成一件事情而不是检查每个请求。

Lee*_*ley 8

在定义/包括路由之前,先定义一个中间件函数,这样可以避免您在每条路由中检查有效会话。请参阅下面的代码,以获取有关如何执行此操作的示例。

如果某些路由是公共的,即它们不需要用户进行有效的会话,则在“使用”中间件函数之前定义这些路由

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
Run Code Online (Sandbox Code Playgroud)

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

选项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) { ... });
Run Code Online (Sandbox Code Playgroud)

选项2在某处定义您的Middlware函数,并在需要时要求它

/middleware.js

module.exports = function (req, res, next) {
    //Do your session checking...
    next();
};
Run Code Online (Sandbox Code Playgroud)

现在,您可以随时随地要求它。

/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;
Run Code Online (Sandbox Code Playgroud)

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


vka*_*v15 5

Express 路由器有一个简洁的use()功能,可以让您为所有路由定义中间件router.use('/xxxxx', authorize); router.post('/xxxx', 'xxxx');应该管用。