[英]Why are POST requests often sent with the Content-type set to urlencoded?
[英]Why does my express POST endpoint return 404 when Content-Type is set by requester?
我有一個快遞服務器:
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);
以及前端獲取請求:
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})
});
如果我在獲取時注釋掉Content-Type
,我會收到“Hello World”響應,但服務器會將 req.body 記錄為空 object。
如果我保持Content-Type
處於獲取狀態,我會得到 404。
為什么設置 Content-Type 會使 express 返回 404 而不設置它返回“Hello World”?
提出問題,得到更好的回應( https://github.com/expressjs/express/issues/4590 )
問題是app.post(/city\/get-ids/g
g
你可以在這里看到更多關於為什么: 為什么帶有全局標志的 RegExp 會給出錯誤的結果?
無論如何,解決方案是刪除g
:
app.post(/city\/get-ids/, (req, res) => {
console.log(req.body);
res.send('Hello World!')
});
后人評論的舊帖子:
好吧。 修復了它,但它仍然絕對零意義。
這是修復:
app.post("/city/get-ids*", (req, res) => {
console.log(req.body);
res.send('Hello World!')
})
出於某種原因,如果設置了 Content-Type,RegExp 版本就不起作用。 無論哪種方式,OPTIONS 預檢都正確返回。 如果沒有 Content-Type,則 POST 路由正確匹配。 但是設置 Content-Type 時,用於 POST 路由的 RegExp 不再起作用。
這完全沒有意義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.