Search code examples
node.jsexpress

nodejs express: can initiative programmatically response a cannot post response?


I'm using Node.js and express to write a website.

I have a post URL interface, and I want this URL interface to act:

When accessing this URL but without the correct params, I want a response just like this URL interface does not exist.

Can this be achieved?


Solution

  • You could explicitly return a 404 response:

    app.post('/route', (req, res) => {
        if (req.body.requiredParam !== 'something expected') {
            res.status(404).end();
        }
        // Continue handling the request if the params are OK
    });
    

    Alternatively, and arguably more elegantly, if you have a finalhandler that issues a 404 for any wrong URL, you could pass the request on to it:

    app.post('/route', (req, res, next) => {
        if (req.body.requiredParam !== 'something expected') {
            next();
        }
        // Continue handling the request if the params are OK
    });