HTTP请求的JSON响应主体在服务器端已失真。它有一个键,其元素是一个数组。这是我使用jQuery ajax的HTTP请求:
function dbInsert(event_arr) {
$.ajax({
url: "http://localhost:5000/insertdata",
type: "POST",
data: JSON.stringify(event_arr),
success: function(events) {
console.log("TestInsert was successfully executed");
},
error: function(textStatus, errorThrown) {
console.error("The following error occurred: " + textStatus, errorThrown);
}
});
当我将JSON.stringify(event_arr)打印到控制台时,它是这样的:
{"results": [{"event_client": "name1","event_date": "date1"}, {"event_client": "name2", "event_date": "date2"}]}
然后,在服务器端,这是我尝试理解响应主体并使用JSON格式的各种尝试:
// returns [object, Object], cannot be passed into JSON.parse
console.log(request.body);
var temp = JSON.stringify(request.body);
var temp2 = JSON.parse(temp);
// prints {"{\"results\":":{"{\"event_name\":\"name1\",\"event_date\":\"date1\"},{\"event_name\":\"name2\",\"event_date\":\"date2\"}":""}}
console.log(temp);
// prints { '{"results":': { '{"event_name":"name1","event_date":"date1"},{"event_name":"name2","event_date":"date2"}': '' } }
console.log(temp2);
在dbInsert()中调用的JSON.stringify()似乎弄乱了JSON的读取方式,而我却不解决该内部格式错误!
您需要contentType: "application/json"
在$.ajax({})
函数中设置:。
像这样:
function dbInsert(event_arr) {
$.ajax({
url: "http://localhost:5000/insertdata",
type: "POST",
data: JSON.stringify(event_arr),
contentType: "application/json",
success: function(events) {
console.log("TestInsert was successfully executed");
},
error: function(textStatus, errorThrown) {
console.error("The following error occurred: " + textStatus, errorThrown);
}
});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句