expressJS:限制可接受的内容类型

sam*_*mol 3 node.js express

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

application/x-www-form-urlencoded

application/json

有没有一种方法可以表示强制只接受两个标头并拒绝任何其他POST请求并以某种 400 错误响应?

msc*_*dex 5

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

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