我正在尝试一些简单的事情,我使用 fetch API 从我的应用程序的前端发出请求,就像这样
let request = new Request('http://localhost:3000/add', {
headers: new Headers({
'Content-Type': 'text/json'
}),
method: 'GET'
});
fetch(request).then((response) => {
console.log(response);
});
我像这样在服务器上处理这个请求,
app.get('/add', (req, res) => {
const data = {
"number1": "2",
"number2": "4"
};
res.send(data);
});
但是,当我尝试在前端 console.log(response) 上访问我的数据时,我得到以下对象
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
响应主体为空。我以为那是数据会出现的地方?如何有效地从服务器传递数据?
原文由 random_coder_101 发布,翻译遵循 CC BY-SA 4.0 许可协议
好的,这适用于我的前端
关键部分是承诺链的解析。
此处的类似问题 JavaScript fetch API - Why does response.json() return a promise object (instead of JSON)?