[英]JSON data array in req.body
所以我試圖將 json 數據傳遞給我的req.body
數據如下所示:
answers = ["A","B"]; //This is an array that will be added to the JSON Object
var Student_Answers = { //This is the JSON object
Answers: answers,
matricNumber: matric
};
這是帖子請求:
$.ajax({
type: "POST",
url: `/exam/${matric2}`,
dataType: "json",
data: Student_Answers,
success: function(data) {
console.log("data received: ", data);
}
});
所以數據成功傳遞給req.body
但我的問題是數據在req.body
輸出中的req.body
,當我記錄req.body
它看起來像這樣:
{
'Answers[]': [ 'A', 'B' ],
matricNumber: '88/2386'
}
但我所期待的
{
Answers: [ 'A', 'B' ],
matricNumber: '88/2386'
}
有人可以向我解釋為什么在req.body
('Answers[]': [ 'A', 'B' ])
中以這種方式查看答案數組。它搞砸了我將數據保存到 mongodb 的過程。
dataType
告訴jQuery的那種你希望在響應返回的數據是什么。 要告訴 jQuery 您在請求中發送的數據類型,請設置contentType
。 (是的,這是混淆的是data
是發送數據,但dataType
是你期望的響應類型API失敗😊。)您還需要自己字符串化它,jQuery將不會為你做:
$.ajax({
type: "POST",
url: `/exam/${matric2}`,
contentType: "application/json", // <===========
data: JSON.stringify(Student_Answers), // <===========
success: function(data) {
console.log("data received: ", data);
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.