[英]node server cannot find the data in the body
我從 fetch 發送了一個 post 請求,但是 nodejs 服務器無法從 post 請求訪問正文。 我試過 req.body 但它只返回空括號。
const express = require('express');
const bodyParser=require("body-parser");
const app = express();
app.use(bodyParser.urlencoded({ extended: true}))
app.use(bodyParser.json());
app.use(express.json());
app.get("/user",function(req,res){
res.send("just Checking");
});
app.post("/user", (req, res) => {
console.log(req.body);
res.send("got the data");
});
app.listen(3000,function(res){
console.log("server is workig a t local host 3000");
});
這是瀏覽器端代碼
const checking = { name:"badmintion" }
function yo (){
fetch("/user",{
method : "POST",
Headers : {
'Content-Type':'application/json'
},
body: JSON.stringify(checking)
})
}
yo();
在瀏覽器中,我可以看到正在發送數據,但我無法在 nodejs 服務器中接收它,它只顯示空括號。
編輯:我能夠在我的機器上本地重新創建服務器代碼。 我沒有發現任何問題。 我使用 Postman 將 JSON 發送到/user
路由。 您可能遇到的問題在前端。
Headers
應該是小寫的。 你把它大寫了:
...
fetch("/user",{
method : "POST",
headers : {
...
}
...
為了更好地避免 (parse json) 的任何沖突,完全刪除正文解析器並重試。
根據斯坦利的要求,標題設置為小寫。 這將是工作。
本教程可能對您有所幫助:
https://www.geeksforgeeks.org/express-js-express-json-function/amp/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.