【问题标题】:fetch is not giving the correct JSON response in ReactJS? [closed]fetch 没有在 ReactJS 中给出正确的 JSON 响应? [关闭]
【发布时间】:2018-03-10 12:37:02
【问题描述】:

我正在尝试在 API 端点上使用 fetch 方法,但我遇到了一些意外错误。我无法在浏览器的控制台中查看 JSON 数据。

app.js:

import React, { Component } from 'react';
import './App.css';

class App extends Component {

    componentDidMount() {
        fetch('www.flymine.org/query/service/search?q=BRCA1')
            .then(res => res.json())
            .then(res => {
                console.log(res)
            })
    }

  render() {
    return (
      <div>

      </div>
    );
  }
}

export default App;

错误截图:

【问题讨论】:

  • 你能显示data json 对象吗?
  • 第一步是检查网络选项卡或服务器上的响应。不管是什么,它都不是 JSON。
  • @Striped 看看我已经添加了。
  • @stonerock:文字截图没用;正如 Andreas 所说,显然回来的不是 JSON。例如,它可以是标记为 HTML 的 JSON(可能是第一个字符 &lt;,这将适合错误消息)。另外,那个 URL 是你真正使用的吗?因为localhost:3000/data 看起来很奇怪,我希望至少//localhost:3000/data
  • 截图显示localhost,您的示例使用flymine.org。请求的真正设置是什么... - 尽管如此,带有 flymine.org 的 fetch(...)(在修复 url 之后)可以正常工作而没有解析错误。

标签: javascript reactjs fetch


【解决方案1】:

在网址前添加协议http://,如:

componentDidMount() {
        fetch('http://www.flymine.org/query/service/search?q=BRCA1')
            .then(res => res.json())
            .then(res => {
                console.log(res)
            })
    }

【讨论】:

  • 它就像一个魅力
【解决方案2】:

目前,您使用的是页面相对 URL:www.flymine.org/query/service/search?q=BRCA1。这意味着如果您执行该提取,完整的 URL 将类似于http://localhost:3000/www.flymine.org/query/service/search?q=BRCA1。除非您在端口 3000 上运行服务器来执行 Web 请求并返回结果,否则这不是正确的 URL。

要使其与协议相关,请将// 放在它前面。然后它会从页面中获取协议(httphttps)并将//www.flymine.org/query/service/search?q=BRCA1 添加到它,给我们http://www.flymine.org/query/service/search?q=BRCA1https://www.flymine.org/query/service/search?q=BRCA1。或者在它前面加上http://,使其具体为http(因为他们不支持https):

fetch('http://www.flymine.org/query/service/search?q=BRCA1')
  .then(res => res.json())
  .then(res => {
    console.log(res);
  })
  .catch(err => {
    console.error(err);
  });

Live Example on JSBin

请注意,如果您在浏览器中执行此操作,其唯一有效的原因是它们特别允许通过 Cross-Origin Resource Sharing 进行所有来源。如果他们不这样做,您将被Same Origin Policy 阻止。

【讨论】:

  • Crowder 好的答案,谢谢。为什么有人反对我:(
  • @stonerock:不是,你的问题。 :-) 否决按钮上的工具提示是您可能得到的所有解释。编码愉快!
  • @TJ Crowder 但这不好我没有问过重复的问题。如果你喜欢我的问题,请点赞。
  • OP 请求的资源确实有 Access-Control-Allow-Origin: * 标头 btw
  • @AyushGupta:哇!这是jsFiddle。 jsFiddle 使用https 并禁止混合内容; www.flymine.org 不支持 https。所以问题不是 SOP,而是混合内容。我应该多加注意的。没错,在 JSBin 中工作得很好。
猜你喜欢
  • 2022-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-24
  • 1970-01-01
  • 2019-11-02
  • 2021-11-04
  • 1970-01-01
相关资源
最近更新 更多