仅接受 JSON A Post 中的内容类型或将请求放入 ExpressJS

Accept Only JSON Content Type In A Post or Put Request In ExpressJS

我正在使用 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

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

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

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 configuration options

中的 type 选项
app.use(bodyParser.json({
    type: function() {
        return true;
    }
}));

备选方案可以使用通配符

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