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

f45qwnt8  于 2023-01-20  发布在  Node.js
关注(0)|答案(4)|浏览(138)

我想要它做什么。

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...
    //
});

那么我如何设置一个中间件来检查会话,我想让事情更通用一点,想让一个授权函数做一件事,而不是检查每个请求,有什么建议吗?

q5lcpyga

q5lcpyga1#

在你定义/包含你的路由之前定义一个中间件函数,这将避免你在每个路由中检查一个有效的会话。参见下面的代码来了解如何做到这一点。
如果某些路由是公共的,即它们不要求用户具有有效会话,则在"使用“中间件函数之前定义这些路由

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;

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

bxjv4tth

bxjv4tth2#

快速路由器有一个简洁的use()函数,可以为所有路由定义middleware

new9mtju

new9mtju3#

中间件:
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
});
ao218c7q

ao218c7q4#

你可能已经得到了你想要的答案,但我还是会放弃这个

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

相关问题