Wednesday 24 May 2017

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



via Travis

No comments:

Post a Comment