Search code examples
node.jsexpresspostroutermiddleware

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.

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

Solution

  • 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.