node.js 如何使用 ExpressJS 检查 Content-Type?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23271250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 17:12:52  来源:igfitidea点击:

How do I check Content-Type using ExpressJS?

node.jsexpress

提问by JuJoDi

I have a pretty basic RESTful API so far, and my Express app is configured like so:

到目前为止,我有一个非常基本的 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);

How/where can I add middleware that stops a request from reaching my app.postand app.getif the content type is not application/json?

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

The middleware should only stop a request with improper content-type to a url that begins with /api/.

中间件应该只停止对以/api/.

回答by Willie Chalmers III

If you're using Express 4.0 or higher, you can call request.is()on requests from your handlers to filter request content type. For example:

如果您使用 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
    }
});

回答by mscdex

This mounts the middleware at /api/(as a prefix) and checks the content type:

这将中间件挂载在/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();
});

回答by Yuriy Nemtsov

As an alternative, you can use the express-ensure-ctypemiddleware:

作为替代方案,您可以使用express-ensure-ctype中间件:

const express = require('express');
const ensureCtype = require('express-ensure-ctype');

const ensureJson = ensureCtype('json');
const app = express();

app.post('/', ensureJson, function (req, res) {
  res.json(req.body);
});

app.listen(3000);

回答by xpapazaf

For input validation a good module is express-validator. It provides the middlewares needed to do any kind of check. In your case something like:

对于输入验证,一个很好的模块是express-validator。它提供了进行任何类型检查所需的中间件。在你的情况下是这样的:

const { check, validationResult } = require('express-validator')
app.use('/api/', [
   check('content-type').equals('application/json')
 ], function(req, res, next) {
   const errors = validationResult(req);
   if (!errors.isEmpty()) {
     return res.status(422).json({ errors: errors.array() });
   }
   next();
});