【发布时间】:2016-08-18 20:00:27
【问题描述】:
我有一个 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); });
问题是.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); });
和.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 开发工具:
【问题讨论】:
标签: javascript fetch-api