React Fetch:获取json结果但显示网络错误

问题描述 投票:0回答:2

我花了一天在我的本地机器上设置ssl。我正在运行一个wamp栈来在本地构建一个api进行测试。此端点现在已设置为ssl并且工作正常。我有一个简单的路由设置,返回一个json响应。

https://localhost/api/test

它通过访问该地址通过Firefox工作。

现在,我正在运行一个反应应用程序

localhost:3000

我遇到的问题是我正在尝试使用fetch() api并使用在反应网站(https://reactjs.org/docs/faq-ajax.html)上找到的示例。这是代码,但它非常简单。

import React, { Component } from "react";

class Api extends Component {
  constructor(props) {
    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      items: []
    };
  }

  componentDidMount() {
    fetch("https://localhost/api/test")
      .then(res => res.json())
      .then(
        result => {
          this.setState({
            isLoaded: true,
            items: result.items
          });
        },
        // Note: it's important to handle errors here
        // instead of a catch() block so that we don't swallow
        // exceptions from actual bugs in components.
        error => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      );
  }

  render() {
    const { error, isLoaded, items } = this.state;
    if (error) {
      return <div>Error: {error.message}</div>;
    } else if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
      return (
        <ul>
          {items.map(item => (
            <li key={item.name}>
              {item.name} {item.price}
            </li>
          ))}
        </ul>
      );
    }
  }
}

export default Api;

踢球者,如果我看一下控制台,我会从请求获得200响应代码,并且还会获得具有正确数据的实际JSON响应....但由于某些原因,在应用程序中,它在尝试获取时会打印NetworkError资源。

如果它没有得到正确的响应或代码,我会理解错误,但这只是没有意义。

任何建议都会有所帮助和赞赏!

json reactjs ssl localhost fetch
2个回答
0
投票

好吧,它看起来像是一个CORS问题......我认为这不是一个问题,因为一切都是本地的。我不得不将以下内容添加到我的Flight Api后端。

Flight::before('json', function () {
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET,PUT,POST,DELETE');
    header('Access-Control-Allow-Headers: Content-Type');
});

0
投票

您必须确保在您的HTTP标头中启用了CORS,您可以从服务器端执行此操作,而对于客户端,您只需要在fetch api调用中编写模式:'cors',因为服务器会抛出错误并且您的浏览器将无法加载为请求的客户端提供的内容。

© www.soinside.com 2019 - 2024. All rights reserved.