簡體   English   中英

節點服務器找不到正文中的數據

[英]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/

確保您以 JSON 格式發送數據,以便 express 可以將其解析為 object: 在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM