【问题标题】:Accept Only JSON Content Type In A Post or Put Request In ExpressJS在 ExpressJS 中仅接受 JSON 内容类型或在 ExpressJS 中提出请求
【发布时间】:2016-10-05 00:57:46
【问题描述】:

我正在使用 ExpressJS 框架来创建 REST API。对于 POST、PUT 和 PATCH 类型的请求方法,所有 API 都应仅接受 JSON 请求正文。

我正在使用 express.bodyParser 模块来解析 JSON 正文。它工作得很好。

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

如果我的 JSON 正文中有任何语法错误,我的最后一个错误处理程序中间件会被完美调用,我可以将响应自定义为 400 Bad Request

但是,如果我传递内容类型而不是 application/json 之类的 (text/plain,text/xml,application/xml),则正文解析器模块会正确解析它,并且在这种情况下不会调用我的错误处理程序中间件。

我最后一个错误处理中间件:

export default function(error, request, response, next) {
  if(error.name == 'SyntaxError') {
    response.status(400);
    response.json({
      status: 400,
      message: "Bad Request!"
    });
  }
  next();
}

如果内容类型不是applicaition/json,我想做的是调用我的最后一个错误处理程序中间。

【问题讨论】:

  • 你只需要给bodyParser.json添加适当的配置选项,看看我的回答。

标签: node.js express body-parser


【解决方案1】:

为此,您只需使用bodyparser.json configuration options 中的type 选项

app.use(bodyParser.json({
    type: function() {
        return true;
    }
}));

替代方法可以使用通配符

app.use(bodyParser.json({
    type: "*/*"
}));

【讨论】:

  • 澄清为什么这样做。这基本上告诉 json bodyparser 尝试解析“所有的东西”,如果它不是有效的 json,则会抛出错误。
猜你喜欢
  • 2015-10-15
  • 2019-02-09
  • 1970-01-01
  • 1970-01-01
  • 2016-05-20
  • 2018-05-12
  • 1970-01-01
  • 1970-01-01
  • 2013-09-02
相关资源
最近更新 更多