JSON不会加载React

时间:2018-01-24 23:18:51

标签: ruby-on-rails json reactjs fetch

我有一个Rails 5.1应用程序,通过webpacker安装了React。我有一个资源,我有一个JSON端点,但当我尝试拉这个,我在终端上收到一个错误:

我正在使用fetch("roasts.json")的本地路径 Completed 401 Unauthorized in 7ms (ActiveRecord: 2.0ms)

或者,如果我使用完整路径fetch("https://www.gourmetcoffee.london/roasts.json"),我在终端中没有收到任何错误,但在浏览器中收到Error: NetworkError when attempting to fetch resource.

我从www.reactjs.org获得了很多代码:

import React from 'react'
import ReactDOM from 'react-dom'

class AllRoasts extends React.Component {

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

  componentDidMount() {
    fetch("roasts.json")
      //.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>Brewing...</div>;
    } else {
      return (
        <ul>
          {items.map(item => (
            <li key={id}>
              {item.name}
            </li>
          ))}
        </ul>
      );
    }
  }
}


export default AllRoasts

0 个答案:

没有答案