[英]Why does my express POST endpoint return 404 when Content-Type is set by requester?
I have an express server:我有一个快递服务器:
import express from "express";
const app = express()
const port = 3000;
app.use(express.json())
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "*");
next();
});
app.post(/city\/get-ids/g, (req, res) => {
console.log(req.body);
res.send('Hello World!')
})
app.listen(port);
as well as a front end fetch request:以及前端获取请求:
const response = await fetch('http://localhost:3000/city/get-ids/', {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify({a: 1})
});
If I comment out Content-Type
on the fetch, I get a "Hello World" response, but the server logs req.body as being an empty object.如果我在获取时注释掉
Content-Type
,我会收到“Hello World”响应,但服务器会将 req.body 记录为空 object。
If I keep the Content-Type
on fetch, I get a 404.如果我保持
Content-Type
处于获取状态,我会得到 404。
Why does setting Content-Type make express return a 404 while not setting it returns "Hello World"?为什么设置 Content-Type 会使 express 返回 404 而不设置它返回“Hello World”?
Put in an issue, got a better response ( https://github.com/expressjs/express/issues/4590 )提出问题,得到更好的回应( https://github.com/expressjs/express/issues/4590 )
The problem was the global g
in app.post(/city\/get-ids/g
.问题是
app.post(/city\/get-ids/g
g
You can see more about why here: Why does a RegExp with global flag give wrong results?你可以在这里看到更多关于为什么: 为什么带有全局标志的 RegExp 会给出错误的结果?
Anyways, the solution is to just remove the g
:无论如何,解决方案是删除
g
:
app.post(/city\/get-ids/, (req, res) => {
console.log(req.body);
res.send('Hello World!')
});
Old post for comment posterity:后人评论的旧帖子:
Alright.好吧。 Fixed it, but it still makes absolutely zero sense.
修复了它,但它仍然绝对零意义。
Here's the fix:这是修复:
app.post("/city/get-ids*", (req, res) => {
console.log(req.body);
res.send('Hello World!')
})
For some reason the RegExp version just doesn't work if Content-Type is set.出于某种原因,如果设置了 Content-Type,RegExp 版本就不起作用。 The OPTIONS preflight returns correctly either way.
无论哪种方式,OPTIONS 预检都正确返回。 If there's no Content-Type the POST route matches correctly.
如果没有 Content-Type,则 POST 路由正确匹配。 But RegExp for POST routes no longer works when Content-Type is set.
但是设置 Content-Type 时,用于 POST 路由的 RegExp 不再起作用。
It makes absolutely no sense.这完全没有意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.