简体   繁体   English

如何使用POST路由作为中间件

[英]How to use POST route as a middleware

I have 2 routes 我有2条路线

  1. users.js POST api/users users.js POST api/users
  2. auth.js POST api/auth/confirmation auth.js POST api/auth/confirmation

I want to use auth/confirmation as middleware in route /users 我想在路径/users使用auth/confirmation作为中间件

I have tried creating a temporary function and using res.redirect(...) but it throws error Cannot GET .... 我尝试创建一个临时函数并使用res.redirect(...)但它抛出错误Cannot GET ....

I can change the structure of the program to make it work, but I want to make it work this way by using another route as a middleware 我可以更改程序的结构以使其正常运行,但是我想通过使用另一条路由作为中间件来使其以这种方式工作

Temp function that I tried 我尝试过的Temp函数


    checkk = (req, res, next) => {

        console.log('middleware')
        res.redirect('api/auth/confirmation')
        next()
    }

auth/auth.js auth / auth.js


    router.post('/confirmation', (req,res)=>{
        //do something
    })

/users.js /users.js


    router.post('/', auth.checkk, async (req, res) => {
        res.send("user route")
    })

Exptected Output 预期输出

middleware
confirm route (If some error occurs it will go back with response)
user route

I dont want users to hit /auth/confirmation endpoint by themselves but via /users . 我不希望用户自己通过/users来访问/auth/confirmation端点。

Edit 编辑

I am using express-validator to check req body, and I want the middleware to check that 我正在使用express-validator检查请求正文,并且我希望中间件检查

router.post('/confirmation', [
    check('name', 'Name is required').not().isEmpty(),
    check('email', 'Enter valid email').isEmail(),

You wouldn't use a route as middleware but instead a function. 您不会使用路由作为中间件,而是使用一个函数。 A common flow for your auth scenario is: 身份验证方案的常见流程是:

  1. User makes request to access secure route POST /users 用户发出访问安全路由POST /users请求
  2. A first piece of middleware will set a user context eg: 第一部分中间件将设置用户上下文,例如:
function setUserContext(req,res,next) {
    // get user from session or decode a JWT from auth header etc.
    if (user) {
        // user will be available for the lifetime of the request
        req.user = user
    }
    next()
}

Use this middleware across all routes: app.use(setUserContext) 在所有路由上都使用此中间件: app.use(setUserContext)

  1. A second middleware function can be applied to routes which need securing: 第二个中间件功能可以应用于需要保护的路由:
function requireLoggedInUser(req,res,next) {
    if (req.user) {
        return next()
    }
    throw new Error("You need to be logged in")
}

Apply to the users route: app.post('/users', requireLoggedInUser, (req, res) => { ... }) 应用于用户路由: app.post('/users', requireLoggedInUser, (req, res) => { ... })

In this case you wouldn't have the confirmation route but instead two middleware functions. 在这种情况下,您将没有确认路线,而是拥有两个中间件功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM