http - Express - 如何阻止无效的 http 方法?

标签 http express routing

我收到无效的 http 方法(见下文),当路由有效时,这些方法会从我的服务器触发超时错误。有什么方法可以阻止 Express 中的所有无效请求吗?我在谷歌上找不到任何东西。 Invalid http requests

最佳答案

采用白名单方法

// before your other code check supported methods
// assuming these ones are, just add/remove ones to customize
if (!/^(GET|PUT|POST|DELETE)$/.test(req.method)) {
  res.status(400).end('bad request');
  return;
}

// your code goes here now

如果使用 express,则使用中间件

router.use((req, res, next) => {
  if (!/^(GET|PUT|POST|DELETE)$/.test(req.method)) {
    res.status(400).end('bad request');
    return;
  }
  next();
});

唐纳德·拉姆斯菲尔德的话...

Reports that say that something hasn't happened are always interesting to me, because as we know, there are known knowns; there are things we know we know. We also know there are known unknowns; that is to say we know there are some things we do not know. But there are also unknown unknowns – the ones we don't know we don't know. And if one looks throughout the history of our country and other free countries, it is the latter category that tend to be the difficult ones.

tl;dr 重要的是,您只能知道自己知道什么,所以请使用白名单。

关于http - Express - 如何阻止无效的 http 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47340081/

相关文章:

apache - HTTP POST 中的各个字段是否有大小限制?

当由 http 响应返回时,Python zlib 不可解码

ruby-on-rails - 是否可以将外部路由文件包含到主 routes.rb 文件中?

Angular2 无法解析 RouterOutlet : (RouterOutletMap, ViewContainerRef,?,名称的所有参数)

http - PUT 使用流和进度上传文件的字节范围

iOS Safari 在按下浏览器后退按钮后清除表单字段

node.js - 如何处理 node.js/express 中的相对路径?

javascript - Node - 无法在 VSCode 中编译 moment.js(模块和需求问题)

javascript - Express.js 请求主体 __proto__

routing - 如何使用 Symfony Routing 作为独立组件调试路由?