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.
If I keep the Content-Type
on fetch, I get a 404.
Why does setting Content-Type make express return a 404 while not setting it returns "Hello World"?
Put in an issue, got a better response ( https://github.com/expressjs/express/issues/4590 )
The problem was the global g
in app.post(/city\/get-ids/g
.
You can see more about why here: Why does a RegExp with global flag give wrong results?
Anyways, the solution is to just remove the 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. The OPTIONS preflight returns correctly either way. If there's no Content-Type the POST route matches correctly. But RegExp for POST routes no longer works when Content-Type is set.
It makes absolutely no sense.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.