尝试使用fetch访问响应数据 [英] Trying to access response data using fetch
问题描述
我正在尝试一些简单的方法,我使用fetch API从我的应用程序的前端发出请求,如此
I'm trying something simple where I make a request from the front end of my app using the fetch API like so
let request = new Request('http://localhost:3000/add', {
headers: new Headers({
'Content-Type': 'text/json'
}),
method: 'GET'
});
fetch(request).then((response) => {
console.log(response);
});
我在服务器上处理此请求,如此,
I am handling this request on the server like so,
app.get('/add', (req, res) => {
const data = {
"number1": "2",
"number2": "4"
};
res.send(data);
});
然而,当我尝试在前端console.log(响应)上访问我的数据时,我获取以下对象
However, when I try to access my data on the front end console.log(response), I get the following object
Response {type: "basic", url: "http://localhost:3000/add", redirected: false, status: 200, ok: true…}
body:(...)
bodyUsed:false
headers:Headers
ok:true
redirected:false
status:200
statusText:"OK"
type:"basic"
url:"http://localhost:3000/add"
__proto__:Response
响应正文为空。我认为这是数据出现的地方?如何有效地从服务器传递数据?
The response body is empty. I assumed that's where the data would show up? How do I pass data effectively from the server?
推荐答案
好的,这适用于我的前端
Okay, this works on my front end
fetch(request).then((response) => {
console.log(response);
response.json().then((data) => {
console.log(data);
});
});
关键部分是承诺链的解决方案。
The key part was the resolution of the promise chain.
此处类似的问题 JavaScript fetch API - 为什么response.json()返回一个promise对象(而不是JSON)?
这篇关于尝试使用fetch访问响应数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!