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)
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…