【发布时间】:2019-04-28 17:03:17
【问题描述】:
使用 fetch api,node.js 服务器发回以下序列化对象:
app.get('/getJoe', function(request, response) {
var myObj = {};
myObj.firstname = "Joe";
myObj.age = 23;
var myObjSerialized = JSON.stringify(myObj);
response.send(myObjSerialized); //sends {"firstname":"Joe","age":23}
});
fetch API 处理响应如下:
function getJoe(){
fetch('/getJoe')
.then((response) => {
return response.json();
})
.then((person) => {
console.log(typeof(person)); //outputs object
console.log(person) //outputs {firstname: "Joe", age: 23}
})
}
为什么 fetch 渲染字符串化对象的方式与它在服务器上的渲染方式不同?
换句话说,如果服务器使用以下字符串化对象响应获取请求:
{"firstname":"Joe","age":23}
fetch 不应该仍将其视为字符串化吗?为什么将其呈现为:
{名字:“乔”,年龄:23}
此外,不必将 person 转换回对象(使用 JSON.parse(person) ),person 已经可以被视为对象。
【问题讨论】: