Search code examples
javascriptnode.jsexpressroutesmiddleware

how to allow pass through in express handlers?


I have anPOST api endpoint lets say /users to fetch the list of users.

It is POST because body of the request is very huge and might not fit in url for GET request.

suppose the body of user POST have a key called age , which should give me user of certain age ie kind of filtering

now in express i have route like

app.post('/users', function(r,res){
  // function body
})

and i cant actually put any code inside that function body

so i was able to intercept the request by using one more handler for /users and putting it before the original handler but obviously it intercepts all /users requests and breaks earlier functionality

how can i intercept only the request with particular age and then pass through other requests to the original handler, so that original functionality keeps working?

I want to know how can i do this using route handlers and not middlewares ?

i cant mess with the url or request body also


Solution

  • First off, this sounds like a really bad design so really the better way to fix things is to just fix the URL design so you don't have this conflict between code you can and can't modify. I say this because it sounds like you're trying to "hack" into something rather than make a proper design.

    If your code is using the regular body-parser middleware, then the body of the post will already be parsed and in req.body. So, you can look for the desired parameter in req.body.age and check its value.

    If it meets your criteria, then you can process the request and you're done. If it doesn't meet your request, then you call next() to continue processing to other request handlers.

    // make sure this is defined BEFORE other /users request handlers
    app.post('/users', function(req, res, next) {
        // test some condition here
        if (+req.body.age > 30) {
            // process the request and send a response
            res.send("You're too old");
        } else {
            // continue processing to other request handlers
            next();
        }
    })