简体   繁体   English

如何仅在具有Express和Node的POST上添加中间件

[英]How to add a middleware only on POST with Express and Node

I have a middleware that I want to be applied only when the http method is post. 我有一个中间件,我想只在http方法发布时应用。

The following works fine, but I get the feeling there is a better way: 以下工作正常,但我觉得有更好的方法:

'use strict'

const   express = require('express'),
        router = express.Router()


router.use((req, res, next) => {
    if (req.method === 'POST') {
        // do stuff
    }

    return next()
})

module.exports = router

I'd like to do something like this, but it doesn't work: 我想做这样的事情,但它不起作用:

'use strict'

const   express = require('express'),
        router = express.Router()


router.post((req, res, next) => {
    // do stuff

    return next()
})

module.exports = router

You can use * symbol: 你可以使用*符号:

const express = require('express')
const app = express();

app.post('*', (req, res, next) => {
  console.log('POST happen')
  next();
})

app.post('/foo', (req, res) => {
  res.send('foo');
});

app.post('/bar', (req, res) => {
  res.send('bar');
});

app.listen(11111);

This will respond with "foo" string on POST /foo and with "bar" string on POST /bar but always log "POST happen" to console. 这将在POST /foo上使用“foo”字符串进行响应,在POST /bar上使用“bar”字符串进行响应,但始终将“POST occurrence”发送到控制台。

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

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