Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 924
twharmon Avatar asked May 24 '17 09:05

twharmon


1 Answers

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.

like image 58
Glen Swift Avatar answered Oct 10 '22 04:10

Glen Swift