react fetch给出一个空的响应体 [英] react fetch gives an empty response body
问题描述
我有一个react / redux应用程序,我正在尝试向服务器发出一个简单的GET请求:
I have a react/redux application and I'm trying to do a simple GET request to a sever:
fetch('http://example.com/api/node', {
mode: "no-cors",
method: "GET",
headers: {
"Accept": "application/json"
}
}).then((response) => {
console.log(response.body); // null
return dispatch({
type: "GET_CALL",
response: response
});
})
.catch(error => { console.log('request failed', error); });
问题是 .then()中的响应正文是空的
功能,我不知道为什么。我在网上检查了一些例子,看起来我的代码应该可行,所以我显然在这里遗漏了一些东西。
问题是,如果我检查Chrome的开发工具中的网络选项卡,请求已经完成,我会收到我正在寻找的数据。
The problem is that the response body is empty in the .then()
function and I'm not sure why. I checked examples online and it looks like my code should work so I'm obviously missing something here.
The thing is, if I check the network tab in Chrome's dev tools, the request is made and I receive the data I'm looking for.
可以有人在这个上发光吗?
Can anybody shine a light on this one?
编辑:
我试过转换响应。
使用 .text()
:
fetch('http://example.com/api/node', {
mode: "no-cors",
method: "GET",
headers: {
"Accept": "application/json"
}
})
.then(response => response.text())
.then((response) => {
console.log(response); // returns empty string
return dispatch({
type: "GET_CALL",
response: response
});
})
.catch(error => { console.log('request failed', error); });
和 .json()
:
fetch('http://example.com/api/node', {
mode: "no-cors",
method: "GET",
headers: {
"Accept": "application/json"
}
})
.then(response => response.json())
.then((response) => {
console.log(response.body);
return dispatch({
type: "GET_CALL",
response: response.body
});
})
.catch(error => { console.log('request failed', error); }); // Syntax error: unexpected end of input
查看chrome dev工具:
Looking in the chrome dev tools:
推荐答案
我刚刚遇到这个。如本答案所述,使用模式:no-cors
会给你一个 opaque响应
,它似乎不会返回正文中的数据。
I just ran into this. As mentioned in this answer, using mode: "no-cors"
will give you an opaque response
, which doesn't seem to return data in the body.
opaque:对跨域资源的no-cors请求的响应。
严格限制。
在我的情况下,我使用 Express
。我安装 cors for Express 并配置它并删除模式后:no-cors
,我收到了一份承诺。响应数据将在承诺中,例如
In my case I was using Express
. After I installed cors for Express and configured it and removed mode: "no-cors"
, I was returned a promise. The response data will be in the promise, e.g.
fetch('http://example.com/api/node', {
// mode: 'no-cors',
method: 'GET',
headers: {
Accept: 'application/json',
},
},
).then(response => {
if (response.ok) {
response.json().then(json => {
console.log(json);
});
}
});
这篇关于react fetch给出一个空的响应体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!