11

I have a middleware that I want to be applied only when the http method is post.

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
twharmon
  • 4,153
  • 5
  • 22
  • 48

1 Answers1

24

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.

Boris Zagoruiko
  • 12,705
  • 15
  • 47
  • 79