gpt4 book ai didi

node.js - express JS : Limit acceptable content-types

转载 作者:搜寻专家 更新时间:2023-11-01 00:32:44 25 4
gpt4 key购买 nike

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

application/x-www-form-urlencoded

应用程序/json

有没有一种方法可以让我强制仅接受这两个 header 并拒绝任何其他 POST 请求并以某种 400 错误响应?

最佳答案

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

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();
});

关于node.js - express JS : Limit acceptable content-types,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23190659/

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