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

后端 未结 6 1146
孤城傲影
孤城傲影 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 03:03

    Due to ambiguity, there really is no other way. Personally, I would do something like this:

    var route = '/page/:id/comments'
    app.get(route, getComments)
    app.all(route, send405)
    
    function send405(req, res, next) {
      var err = new Error()
      err.status = 405
      next(err)
    }
    

    Either way, you have to check the routes twice.

提交回复
热议问题