[英]JSON parse on a JSON string throws “Cannot convert object to primitive value”
server.js
使用主體解析器中間件,車把和快遞
路線
module.exports = function (app) {
app.post('/questionnaire/submit', function (req, res) { // Ajax Call
var data = JSON.parse(req.body);
res.send({});
});
};
客戶
function submitData() { // Send a data object to the server
$.ajax({
type: 'POST',
url: '/questionnaire/submit',
dataType: "json",
data: JSON.stringify({
satisfactory: "text 1",
improvement: "text 2",
rating: 0.7
})
}).done(function () {
$(location).attr('href', '/sendOff');
}).fail(function () {
});
}
記錄req.body
我得到一個JSON字符串
{'{“滿意”:“文本1”,“改進”:“文本2”,“等級”:0.7}':“”}
我嘗試將此字符串解析為一個對象。 這樣做時,我會收到此錯誤消息
TypeError: Cannot convert object to primitive value at JSON.parse (<anonymous>) at C:\\Users\\mah\\Desktop\\FeedbackTool\\Server\\Routes\\questionnaire.js:12:25 at Layer.handle [as handle_request] (C:\\Users\\mah\\node_modules\\express\\lib\\router\\layer.js:95:5) at next (C:\\Users\\mah\\node_modules\\express\\lib\\router\\route.js:137:13) at Route.dispatch (C:\\Users\\mah\\node_modules\\express\\lib\\router\\route.js:112:3) at Layer.handle [as handle_request] (C:\\Users\\mah\\node_modules\\express\\lib\\router\\layer.js:95:5) at C:\\Users\\mah\\node_modules\\express\\lib\\router\\index.js:281:22 at Function.process_params (C:\\Users\\mah\\node_modules\\express\\lib\\router\\index.js:335:12) at next (C:\\Users\\mah\\node_modules\\express\\lib\\router\\index.js:275:10) at C:\\Users\\mah\\node_modules\\body-parser\\lib\\read.js:130:5
那么如何將字符串解析為對象呢?
通常我會執行JSON.parse(req.body)
。
由於您正在使用body-parser
中間件,因此您req.body
再次解析req.body
,因為它已經由body-parser
進行了body-parser
例
如果您使用了app.use(bodyParser.json())
那么你只需要這樣做
module.exports = function (app) {
app.post('/questionnaire/submit', function (req, res) { // Ajax Call
var data = req.body; // this is already parsed and is an object
res.send({});
});
};
正如@TJ Crowder指出的那樣,您還應該發送正確的contentType
以便body-parser
知道其json
function submitData() { // Send a data object to the server
$.ajax({
type: 'POST',
url: '/questionnaire/submit',
contentType: 'application/json',
data: JSON.stringify({
satisfactory: "text 1",
improvement: "text 2",
rating: 0.7
})
}).done(function () {
$(location).attr('href', '/sendOff');
}).fail(function () {
});
}
您需要設置正確的contentType:
$.ajax({
type: 'POST',
url: '/questionnaire/submit',
contentType: 'application/json',
data: JSON.stringify({ satisfactory: "text 1", rating: 0.7 })
});
app.post('/questionnaire/submit', function (req, res) { // Ajax Call
var data = JSON.parse(req.body);
console.log(data.rating); // 0.7
res.send(data);
});
另外,使用body-parser
可以避免在服務器端link上進行JSON.parse
調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.