Raz*_*lin 47 javascript fetch-api
我有一个react/redux应用程序,我正在尝试对服务器执行简单的GET请求:
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); });
Run Code Online (Sandbox Code Playgroud)
问题是.then()函数中的响应体是空的,我不知道为什么.我在网上检查了一些例子,看起来我的代码应该可行,所以我显然在这里遗漏了一些东西.问题是,如果我检查Chrome的开发工具中的网络选项卡,则会发出请求并收到我正在寻找的数据.
任何人都可以对这一个发光吗?
编辑:
我尝试转换响应.
使用.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); });
Run Code Online (Sandbox Code Playgroud)
并与.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
Run Code Online (Sandbox Code Playgroud)
查看chrome开发工具:
Rat*_*ica 107
我刚碰到这个.正如在这个答案中提到的,使用mode: "no-cors"会给你一个opaque response,它似乎不会返回正文中的数据.
opaque:对跨域资源的"no-cors"请求的响应. 严重受限制.
就我而言,我正在使用Express.在为Express安装cors并配置并删除后mode: "no-cors",我收到了一个承诺.响应数据将在承诺中,例如
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);
});
}
});
Run Code Online (Sandbox Code Playgroud)
Nai*_*han 21
在您可以访问之前,您需要转换response为jsonresponse.body
来自文档
fetch(url)
.then(response => response.json())
.then(json => {
console.log('parsed json', json) // access json.body here
})
Run Code Online (Sandbox Code Playgroud)
ope*_*onk 19
这需要更改前端 JS 和后端发送的标头。
前端
删除"mode":"no-cors"获取选项。
fetch(
"http://example.com/api/docs",
{
// mode: "no-cors",
method: "GET"
}
)
.then(response => response.text())
.then(data => console.log(data))
Run Code Online (Sandbox Code Playgroud)
后端
当您的服务器响应请求时,请包含指定请求来源的 CORS 标头。如果您不关心来源,请指定通配符*。
原始响应应包含这样的标头。
Access-Control-Allow-Origin: *
Run Code Online (Sandbox Code Playgroud)
您必须阅读响应的正文:
fetch(url)
.then(res => res.text()) // Read the body as a string
fetch(url)
.then(res => res.json()) // Read the body as JSON payload
Run Code Online (Sandbox Code Playgroud)
阅读身体后,您将可以对其进行操作:
fetch('http://example.com/api/node', {
mode: "no-cors",
method: "GET",
headers: {
"Accept": "application/json"
}
})
.then(response => response.json())
.then(response => {
return dispatch({
type: "GET_CALL",
response: response
});
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
77993 次 |
| 最近记录: |