在ExpressJS中仅接受JSON内容类型的发布或放置请求

Man*_*gir 6 node.js express body-parser

我正在使用ExpressJS框架来创建REST API.所有API都应该只接受POST,PUT和PATCH类型的请求方法的JSON请求体.

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

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
Run Code Online (Sandbox Code Playgroud)

如果我的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();
}
Run Code Online (Sandbox Code Playgroud)

我想要做的是在内容类型不是的情况下调用我的最后一个错误处理程序applicaition/json.

gev*_*org 9

要做到这一点,你只需要使用type选项从bodyparser.json配置选项

app.use(bodyParser.json({
    type: function() {
        return true;
    }
}));
Run Code Online (Sandbox Code Playgroud)

替代方案可能是使用通配符

app.use(bodyParser.json({
    type: "*/*"
}));
Run Code Online (Sandbox Code Playgroud)

  • 澄清为什么这有效.这基本上告诉json bodyparser尝试解析"所有的东西",如果它不是有效的json会抛出错误. (3认同)