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



我要它做什么。

 router.post('/xxxx', authorize , xxxx);
  function authorize(req, res, next)
   {
    if(xxx)
        res.send(500);
    else
     next(); 
   }

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

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

因此,我如何设置将检查会话的中间件,我想让事情变得更通用,并希望让单个授权函数执行单个事情,而不是在每个请求中检查任何建议。任何建议。

在定义/包括路由之前定义一个中间软件功能,这将避免在每个路由中检查有效的会话。有关如何执行此操作的示例,请参见下面的代码。

如果某些路线是公开的,即他们不需要用户具有有效的会话,然后在"使用"中间软件功能之前定义这些会话

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 在某个地方定义您的中间软件功能,并在需要的地方需要它

/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;

希望您能为如何实现此功能提供一般的了解。

Express路由器具有整洁的use()功能,可让您为所有路由定义中间件。router.use('/xxxxx', authorize); router.post('/xxxx', 'xxxx');应该工作。

中间件:
samplemiddleware.js

export const verifyUser = (req, res, next) => {
   console.log('Verified')
   next();
}

路线

import express from 'express';
import { verifyUser } from './sampleMiddleware.js';
const userRoutes = express.Router();
userRoutes.route('/update').put(verifyUser, async function(){
     //write your function heere
});

我们可以以以下方式使用它

router.use(
   routerLevelMiddleware
);
router.route('/endpoint1').get(myEndpoint1Function());
router.route('/endpoint2').get(myEndpoint2Function());

router.route('/').get(routerLevelMiddleware(), myEndpoint1Function());

您可能会得到所需的答案,但我仍然会删除此

router.route('/xxx/xxxx').get(authorize, function(req, res) {...});

最新更新