Fetch 从服务器检索序列化对象。为什么在提取内部检查时它已经反序列化了?
Fetch retrieves a serialized object from the server. Why is it already deserialized when examined inside the 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}
});
提取 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 不应该仍然将其视为字符串化吗?为什么它会呈现为:
{名字:"Joe",年龄:23}
此外,不必将人转换回对象(使用 JSON.parse(person) )人已经可以被视为对象。
return response.json();
行接受 Response
流和 returns 解析为 反序列化 版本的 Promise
响应。如果你只想要纯文本,你可以使用 .text()
方法:
return response.text();
这种自动反序列化是 fetch
和 fetch
的 .json()
方法所特有的。如果您要使用 XMLHttpRequest
,您 将 只有文本响应,您必须使用 JSON.parse
.[=20= 将其转换回对象]
使用提取 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}
});
提取 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 不应该仍然将其视为字符串化吗?为什么它会呈现为:
{名字:"Joe",年龄:23}
此外,不必将人转换回对象(使用 JSON.parse(person) )人已经可以被视为对象。
return response.json();
行接受 Response
流和 returns 解析为 反序列化 版本的 Promise
响应。如果你只想要纯文本,你可以使用 .text()
方法:
return response.text();
这种自动反序列化是 fetch
和 fetch
的 .json()
方法所特有的。如果您要使用 XMLHttpRequest
,您 将 只有文本响应,您必须使用 JSON.parse
.[=20= 将其转换回对象]