Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
443 views
in Technique[技术] by (71.8m points)

node.js - Nodejs handle unsupported URLs and request types

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'});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

// note 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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...