简体   繁体   English

如何在 app.use 中间件中同时使用 get 和 post

[英]How to use get and post both in app.use middleware

I wish to know how can I have both get and post request handled by app.use the way I do it using app.route我想知道如何让app.use处理 get 和 post 请求,就像我使用app.route

app.use('/', (req, res, next) => {
    if (isLaunched) {
        return next()
    }
    // You can also render if you want
    res.render('coming-soon')
});

How can I handle a post request to this?我该如何处理对此的发布请求?

According to https://expressjs.com/en/guide/using-middleware.html the syntax you already have is used for any type of HTTP request - including GET and POST.根据https://expressjs.com/en/guide/using-middleware.html ,您已经拥有的语法可用于任何类型的 HTTP 请求 - 包括 GET 和 POST。 You can detect the method via req.method .您可以通过req.method检测该方法。

app.use() already handles ALL http methods, including GET and POST. app.use()已经处理了所有的 http 方法,包括 GET 和 POST。 You can see exactly which method it is for any given request by checking req.method .通过检查req.method您可以准确地看到它用于任何给定请求的req.method

If you had trouble with some GET or POST when doing this, then please show the specific code and the specific request that it didn't work for.如果您在执行此操作时遇到某些 GET 或 POST 问题,请显示特定代码和它不起作用的特定请求。 If you didn't try it yet, then just try it as it should work just fine.如果你还没有尝试过,那就试试吧,因为它应该可以正常工作。

Middlewares are mounted using app.use(<middleware-name>) so, you can add it to all routes like you do for bodyParser/CORS etc.中间件使用app.use(<middleware-name>)挂载,因此,您可以将其添加到所有路由中,就像为 bodyParser/CORS 等做的那样。

If you want to mount for specific routes you can use如果你想安装特定的路线,你可以使用

app.post("/example" , middleware, (req,res)=>{
    res.send("Hello world")
})

Refer to Use middleware on specific routes请参阅在特定路由上使用中间件

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

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