Nodejs handle unsupported URLs and request types

前端 未结 1 874
失恋的感觉
失恋的感觉 2020-12-12 07:11

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<

相关标签:
1条回答
  • 2020-12-12 07:32

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

    0 讨论(0)
提交回复
热议问题