node.js - express JS : Limit acceptable content-types

标签 node.js express

我有一个 expressJS API。在 POST 路由中,我只接受两种类型的 header :

application/x-www-form-urlencoded

应用程序/json

有没有一种方法可以让我强制仅接受这两个 header 并拒绝任何其他 POST 请求并以某种 400 错误响应?

最佳答案

您可以在每个路由或所有路由的基础上使用像这样的简单中间件:

var RE_CONTYPE = /^application\/(?:x-www-form-urlencoded|json)(?:[\s;]|$)/i;
app.use(function(req, res, next) {
  if (req.method === 'POST' && !RE_CONTYPE.test(req.headers['content-type']))
    return res.send(415);
  next();
});

关于node.js - express JS : Limit acceptable content-types,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23190659/

相关文章:

javascript - 从响应中解析缓存控制 header 值

javascript - Gulp watch 不工作

angularjs - 无法通过 Protractor JS 在 IE11 上运行多重兼容性测试

node.js - 将 Node.JS 缓冲流 block 的二进制数据解析为结构的最快方法是什么?

node.js - 将 .npmrc 文件添加到 Angular 项目

node.js - Express Restful api 需要 json 数组

node.js - MongoDB 和 Cosmos DB 键错误收集

javascript - 使用 expressJS 将数据插入到 MongoDB

node.js - Web 套接字和 Flash 套接字客户端连接到一个 Node.js

mysql - 如何在nodejs回调函数中从mysql获取完整数据