提取给出一个空的响应主体 [英] 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.
有人可以照亮它吗?
我尝试转换响应.
使用.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开发工具:
Looking in the chrome dev tools:
推荐答案
我刚刚遇到了这个问题.如答案所述,使用mode: "no-cors"
将为您提供一个opaque response
,它似乎没有返回数据在体内.
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"请求的响应. 受到严格限制.
opaque: Response for "no-cors" request to cross-origin resource. Severely restricted.
就我而言,我正在使用Express
.安装Express的 cors 并对其进行配置并删除mode: "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);
});
}
});
这篇关于提取给出一个空的响应主体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!