如何使用ExpressJS检查Content-Type?

JuJ*_*oDi 11 node.js express

到目前为止,我有一个非常基本的RESTful API,我的Express应用程序配置如下:

app.configure(function () {
  app.use(express.static(__dirname + '/public'));
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
});

app.post('/api/vehicles', vehicles.addVehicle);
Run Code Online (Sandbox Code Playgroud)

如何/在哪里可以添加阻止请求到达我的中间件app.post以及app.get内容类型不是application/json

中间件只应将具有不正确内容类型的请求停止到以/api/.开头的URL .

Wil*_*III 23

如果您使用的是Express 4.0或更高版本,则可以调用request.is()处理程序的请求来过滤请求内容类型.例如:

app.use('/api/', (req, res, next) => {
    if (!req.is('application/json')) {
        // Send error here
        res.send(400);
    } else {
        // Do logic here
    }
});
Run Code Online (Sandbox Code Playgroud)


msc*_*dex 21

这将中间件安装在/api/(作为前缀)并检查内容类型:

app.use('/api/', function(req, res, next) {
  var contype = req.headers['content-type'];
  if (!contype || contype.indexOf('application/json') !== 0)
    return res.send(400);
  next();
});
Run Code Online (Sandbox Code Playgroud)

  • 我认为应该是:contype.indexOf('application/json') !== 1,因为indexOf在未找到的情况下返回-1,0是有效元素,并且是第一个元素。 (2认同)