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