Sending 405 from express.js when there is a route match but no HTTP method match

后端 未结 6 1145
孤城傲影
孤城傲影 2020-12-30 02:33

I\'m looking for a clean way to have my express app return 405 Method Not Allowed if a client sends a request that matches a mapped url route but does not match the mapped H

6条回答
  •  爱一瞬间的悲伤
    2020-12-30 02:59

    I have been doing it this way:

    Say if you have GET and POST method handlers for /. You can wrap the path with app.route or router.route and assign the handlers accordingly.

        app.route("/").get((req, res) => {
                /* DO SOMETHING*/
        }).post((req, res) => {
                /* DO SOMETHING*/
        }).all((req, res) => {
                res.status(405).send();
        });
    
    • http://expressjs.com/en/4x/api.html#app.route
    • http://expressjs.com/en/4x/api.html#router.route

    A request will get matched to the route and filtered through the handlers. If a handler is present, it will get handled as usual. Else, it will reach the all handler that will set the status code to 405 and ending the request.

提交回复
热议问题