我正在使用 express js,但由于某種原因,服務器正在記錄一個空物件{},而不是我發送的實際 JSON 字串。我使用過很多其他技術,比如燒瓶,這沒有任何意義。
代碼:
function upload () {
fetch("http://localhost:8080/chat", {
method: "POST",
body: JSON.stringify({
name: "Deska",
email: "[email protected]",
phone: "342234553"
})
}).then(result => {
// do something with the result
console.log("Completed with result:", result);
}).catch(err => {
// if any error occured, then catch it here
console.error(err);
});
}
app.post('/chat', function(req, res) {
let test = req.body;
console.log(test);
}
在“上傳”功能上,我沒有記錄任何內容,在服務器中,我得到了{}我提到的一個空物件。
如果您想知道我的問題,我將不勝感激。
謝謝你。
更新:
問題應該在 prontend 中,因為使用郵遞員的作品發送帖子請求。
uj5u.com熱心網友回復:
我認為錯誤可能會發生,因為您缺少Content-Type標題。你可以試試這個:
function upload () {
fetch("http://localhost:8080/chat", {
headers: {
'Content-Type': 'application/json',
},
method: "POST",
body: JSON.stringify({
name: "Deska",
email: "[email protected]",
phone: "342234553"
})
}).then(result => {
// do something with the result
console.log("Completed with result:", result);
}).catch(err => {
// if any error occured, then catch it here
console.error(err);
});
}
您還應該確保在您的服務器中使用express.json中間件,這樣:
app.use(express.json());
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/462327.html
上一篇:入口-連接被拒絕
