Nodejs handle unsupported URLs and request types

2020-02-07 11:24发布

问题:

I would like to add to my web service an option to handle unsupported URLs, I should mention that I'm using Express. In order to handle bad URLs, (code 404), I tried using

app.use(app.router);

But apparently it's deprecated, what other solutions can I use? I saw this suggested solution but I would like to hear about other alternatives first.

In addition, my web service support a few HTTP request types, such as GET and POST, how do I properly respond to request types that I do not support? such as DELETE.

The behavior I would like to have is that in case of 404 error, I will return an appropriate response message that's all. Same in case of unsupported requests.

For example:

response.status(404).json({success: false,msg: 'Invalid URL'});

回答1:

A 404 handler for all unhandled requests in Express would typically look like this:

app.use(function(req, res, next) {
    res.status(404).sendFile(localPathToYour404Page);
});

You just make this the last route that you register and it will get called if no other routes have handled the request.

This will also catch methods that you don't support such as DELETE. If you want to customize the response based on what was requested, then you can just put whatever detection and customization code you want inside that above handler.

For example, if you wanted to detect a DELETE request, you could do this:

app.use(function(req, res, next) {
    if (req.method === "DELETE") {
        res.status(404).sendFile(localPathToYour404DeletePage);
    } else {
        res.status(404).sendFile(localPathToYour404Page);
    }
});

Or, if your response is JSON:

app.use(function(req, res, next) {
    let obj = {success: false};
    if (req.method === "DELETE") {
        obj.msg = "DELETE method not supported";
    } else {
        obj.msg = "Invalid URL";
    }
    res.status(404).json(obj);
});

Some references:

Express FAQ: How do I handle 404 responses?

Express Custom Error Pages


And, while you're at it, you should probably put in an Express error handler too:

// not that this has four arguments compared to regular middleware that
// has three arguments
app.use(function (err, req, res, next) {
  console.error(err.stack)
  res.status(500).send('Something broke!')
});

This allows you to handle the case where any of your middleware encountered an error and called next(err).