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

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

    Kinda old question but here is what i did. I just put this after all my routes but before my 400 handler

    // Handle 405 errors
    app.use(function(req, res, next) {
      var flag = false;
      for (var i = 0; i < req.route.stack.length; i++) {
        if (req.method == req.route.stack[i].method) {
          flag = true;
        }
      }
      if (!flag) {
        err = new Error('Method Not Allowed')
        err.status = 405;
        return next(err)
      }
    
      next();
    });
    

提交回复
热议问题