Javascript 尝试使用fetch访问响应数据
我正在尝试一些简单的方法,使用FetchAPI从应用程序前端发出请求,如下所示Javascript 尝试使用fetch访问响应数据,javascript,node.js,fetch-api,Javascript,Node.js,Fetch Api,我正在尝试一些简单的方法,使用FetchAPI从应用程序前端发出请求,如下所示 let request = new Request('http://localhost:3000/add', { headers: new Headers({ 'Content-Type': 'text/json' }), method: 'GET' }); fetch(request).then((response) => { console.log(res
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);
});
但是,当我尝试访问前端控制台.log(响应)上的数据时,我得到以下对象
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
响应主体为空。我想那就是数据显示的地方?如何有效地从服务器传递数据 好的,这在我的前端有效
fetch(request).then((response) => {
console.log(response);
response.json().then((data) => {
console.log(data);
});
});
关键部分是承诺链的解析
这里类似的问题也可以像这样一分为二
async fetchData() {
let config = {
headers: {
'Accept': 'application/json' //or text/json
}
}
fetch(http://localhost:3000/add`, config)
.then(res => {
return res.json();
}).then(this.setResults);
//setResults
setResults(results) {
this.details = results;
//or: let details = results
console.log(details) (or: this.details)
尝试更改
res.send(数据)代码>至<代码>结束(数据)代码>?非常感谢,它真的很有效。我被困了几个小时,终于找到了它