javascript - Curl 返回正确的响应,浏览器返回 null

标签 javascript google-chrome reactjs

这是问题,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
    });
}

fetch documentation

关于javascript - Curl 返回正确的响应,浏览器返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37734203/

相关文章:

google-chrome - mozilla stub 安装程序如何工作?

google-chrome - Chrome 开发者工具中的黑盒脚本选项

reactjs - 在 react-router V4 中,我如何以编程方式设置查询字符串参数?

reactjs - react 性能: what's a good guide for an upper limit on number of components?

reactjs - 可重复使用的react-redux容器组件

javascript - 使用 Google Feeds API 使用 "tap"在 jquery mobile 中自动生成 feed 列表

javascript - 如何在 AnglujarJS ng-repeater 中选择特定元素?

javascript - 在 Chrome 中使用 jquery 隐藏基本身份验证弹出窗口

javascript - 日期时间选择器和颜色选择器不适用于动态创建

javascript - 两个文本字段,只需填写一个(任一)