我正在使用 NodeJS express 和 React。請求正文的預期輸出是“tipologia”,但它實際上回傳一個空物件。我一直在尋找類似的問題(有很多),但這些都沒有用。
客戶:
function CreateStudyPlan(tipologia){
return new Promise((resolve, reject) => {
fetch((URL '/PianoStudio'), {
method: 'POST',
credentials: 'include',
headers: {
"Access-Control-Allow-Headers" : "Content-Type",
"Access-Control-Allow-Origin": "*"
},
body: JSON.stringify(tipologia),
}).then((response) => {
if (response.ok) {
resolve(null);
} else {
// analyze the cause of error
response.json()
.then((message) => { reject(message); }) // error message in the response body
.catch(() => { reject({ error: "Cannot parse server response." }) }); // something else
}
}).catch(() => { reject({ error: "Cannot communicate with the server." }) }); // connection errors
});
}
服務器:
// set-up the middlewares
app.use(morgan('dev'));
app.use(express.json());
const corsOptions = {
origin: 'http://localhost:3000',
credentials: true,
};
app.use(cors(corsOptions));
const isLoggedIn = (req, res, next) => {
if(req.isAuthenticated())
return next();
return res.status(401).json({ error: 'not authenticated'});
}
app.post('/PianoStudio', isLoggedIn, async (req, res) => {
try {
await dao.createPianoStudio(req.body, req.user.id);
res.status(201).json(req.body);
} catch(err) {
console.log(err);
res.status(503).json({error: `Database error during the creation of piano di studi for user ${req.user.id}.`});
}
});
問題是 req.body 是空的,不應該是(我希望它可以兼職輸出):

插入資料庫顯示 req.user.id 沒問題,而 req.body 是一個空物件:

--
請求 ID 和正文上的 2 個單詞: req.body 應該是
正文:JSON:字串化(tipologia)
來自客戶端,而 req.user.id 由會話通過 isLoggedIn 檢索。
標題上的 2 個單詞:
起初我有
headers: {
'Content-Type': 'application/json',
但它給了我CORS錯誤:
CORS 策略已阻止從源“http://localhost:3001/PianoStudio”獲取從“http://localhost:3000”獲取的訪問權限:請求的資源上不存在“Access-Control-Allow-Origin”標頭. 如果不透明的回應滿足您的需求,請將請求的模式設定為“no-cors”以獲取禁用 CORS 的資源。
所以我將標題更改為
headers: {
"Access-Control-Allow-Headers" : "Content-Type",
"Access-Control-Allow-Origin": "*"
}
作為放置'Content-Type':'application/json',再次回傳CORS錯誤。
uj5u.com熱心網友回復:
您應該嘗試在客戶端中將tipologia 定義為一個物件:
body: JSON.stringify({tip_str: tipologia})
在您的服務器中,您將檢索您的tipologia,如下所示:
dao.createPianoStudio(req.body.tip_str, req.user.id)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/487496.html
上一篇:Binary64無法處理特殊字符discord.js
下一篇:django技術實作按帖子數換行
