简体   繁体   中英

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('/', (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. You can detect the method via req.method .

app.use() already handles ALL http methods, including GET and POST. You can see exactly which method it is for any given request by checking 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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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