【问题标题】:Best way to access API from React App?从 React App 访问 API 的最佳方式?
【发布时间】:2017-03-28 13:54:21
【问题描述】:

我使用 React 应用访问 API 的最佳方式是什么?该 API 目前是在 Golang 中使用 kami 和 mgo 开发的,用于 POST/GET/DELETE 请求。

我希望能够向以下 URL 发出 GET 请求:

http://user:password@localhost:8000/api/v1/systems

在我的 React 应用上并将结果存储在 state 属性中:

this.state = {
    data: //store the data here
}

我还想在页面加载时加载这些数据,所以也许我应该使用 componentDidMount() 函数来处理这个?

我从来没有在 React 上使用过 API 调用,所以我想知道这里是否有人能告诉我一个好的方法?

编辑

我正在使用 React 15.3.2。

编辑#2

我查看了 fetch 来处理请求,但我仍然不确定如何在我的情况下使用它。我已经在 localhost:3000 上运行了 react 应用程序,并且在 localhost:8000 上运行了 api,/api/v1/systems 将返回具有以下格式的 JSON:

{ systems : [ //list of objects ] }

我在 componentDidMount() 中尝试了以下操作:

fetch(myRequest) 
  .then(result => {
    console.log(result);
    //this.setState({ data: result.json() });
    });

不太确定 myRequest 应该是什么(尝试使用 URL 的简单字符串:'http://localhost:8000/api/v1/systems'),我也不确定应用程序运行的端口是否会产生冲突或其他问题。

【问题讨论】:

标签: javascript reactjs fetch


【解决方案1】:

您必须决定一个库来进行 API 调用。一个简单的方法是使用现代浏览器内置的fetch。有一个polyfill 来覆盖较旧的。 jQuery's AJAXSuperAgent 是两种选择。这是一个使用fetch 的简单示例。您只需更改请求的 URL。

class Example extends React.Component {
  constructor() {
    super();
    this.state = { data: {} };
  }
  componentDidMount() {
    var self = this;
    fetch('http://reqres.in/api/users')
      .then(function(response) {
        return response.json()
      }).then(function(data) {
        self.setState({ data }, () => console.log(self.state));
      });
  }
  render() {
    return (
      <div/>
    );
  }
}

ReactDOM.render(<Example/>, document.getElementById('View'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="View"></div>

【讨论】:

  • 尝试此操作时出现以下错误:localhost/:1 Fetch API cannot load http://localhost:8000/api/v1/systems. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 401. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.undefined:1 Uncaught (in promise) TypeError: Failed to fetch at TypeError (native)
  • 所以 React 代码可以工作并发出 GET 请求,但您的服务器不允许 CORS。您需要设置 Access-Control-Allow-Origin 标头。这是a pointer
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-16
  • 2017-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-18
  • 1970-01-01
相关资源
最近更新 更多