gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 23:17:48 26 4
gpt4 key购买 nike

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

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

中间件应该只停止对以 /api/ 开头的 url 的内容类型不正确的请求。

最佳答案

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

关于node.js - 如何使用 ExpressJS 检查 Content-Type?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23271250/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com