这是问题,curl
正在返回正确的响应
curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://localhost:8080/rbuilder
HTTP/1.1 200 OK
Content-Length: 1067
{"rScriptName":"CollegePlan"," .............}
但是,使用 ReactJS,浏览器返回空。
componentWillMount() {
fetch('http://localhost:8080/rbuilder', {
method: 'GET',
mode: 'no-cors',
processData: false,
contentType: "application/json",
cache: false,
accept: "application/json"
}).then((res) => {
console.log('GET response', res);
}, (err) => {
console.log(err);
});
}
但是,我注意到,在“网络”选项卡中,rbuilder
在时间线中出现两次,第二次有正确的“响应”。
我的 fetch 有什么问题?
最佳答案
您缺少一步。
为了获取响应正文,您必须根据需要使用其中一种方法
response.text() - 生成字符串形式的响应文本
response.json() - 产生 JSON.parse(responseText) 的结果
response.blob() - 产生一个 Blob
response.arrayBuffer() - 产生一个 ArrayBuffer
response.formData() - 生成可以转发到另一个请求的 FormData
假设你想要一个 json,你应该这样做
componentWillMount() {
fetch('http://localhost:8080/rbuilder', {
method: 'GET',
mode: 'no-cors',
processData: false,
contentType: "application/json",
cache: false,
accept: "application/json"
})
.then((res) => {
return res.json();
})
.then((body) => {
console.log(body);
})
.catch((error) => {
//whatever
});
}
关于javascript - Curl 返回正确的响应,浏览器返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37734203/