【问题标题】:Fetch API request to my React app获取对我的 React 应用程序的 API 请求
【发布时间】:2018-07-18 10:56:51
【问题描述】:

我正在尝试调用 API 以在 React.js 中在我的网站上显示信息,API 需要读取令牌,但我不知道我必须做什么才能生成令牌,因为我的应用程序不需要任何注册或登录。它就像一个产品目录,您可以对其进行个性化设置。我不太了解这个,因为我是新手,我是自学,所以很抱歉,如果这令人困惑,请随时提出任何问题,我会尽力回答:)

这是我到现在为止的代码:

export class Main extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      models: [],
      isLoaded: false
    };
  }

  componentDidMount() {
    fetch(myUrlAPI)
      .then(res => res.json())
      .then(json => {
        this.setState({
          isLoaded: true,
          models: json
        });
      });
  }

  render() {
    const { isLoaded, models } = this.state;

    if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
      return (
        <div>
          <ul>{models.map(model => <li>{model.name}</li>)};</ul>

          <a href="/sofa">
            <div className="Parcelas">
              <img
                src="../../img/image-card-1@2x.png"
                className="ParcImage"
                alt="sofa"
              />
              <h1>Sofa hipnos</h1>
              <h2>
                1,200<span>€</span>
              </h2>
              <p className="Features">
                w 20.5 x 15.5 x h 19.5 (cm)<br />Pele
              </p>

              <button className="Botao">
                <p className="MostraDepois">See Details</p>
                <span>+</span>
              </button>
              <img
                src="../../img/points.svg"
                className="Decoration"
                alt="points"
              />
            </div>
          </a>
        </div>
      );
    }
  }
}

&lt;ul&gt; 标签中,我只是想测试 json 的结果。

另外,每次我使用.map 制作数组时,都会收到此错误(TypeError: models.map is not a function)或类似错误,您能告诉我为什么吗?

【问题讨论】:

  • models 最初是您所在州的一个数组,所以我猜想您在获取完成时设置为modelsjson 很可能不是一个数组。你能在setState 之前做console.log(json); 看看数据是什么样的吗? needs a token to be read 很难为您提供帮助,因为您还没有告诉我们您使用的是什么 API。
  • console.log(json) 返回了这个:{detail: "Authentication credentials were not provided."}@Tholle
  • 好的。将您的阵列设置为此将不起作用。您可能想在第一个 then 回调中执行一些额外的逻辑,例如then(res =&gt; { if (!response.ok) { throw Error(response.statusText); } else { return res.json(); } }) 并在您的承诺链末尾添加 catch,例如.catch(error =&gt; console.error(error))
  • 返回相同的消息,没有别的...
  • 您使用的是什么 API?

标签: javascript reactjs rest api react-native


【解决方案1】:

尝试这种方式,对于令牌,您需要与后端开发人员确认您应该发送的方式和内容。

 let token = '1234567'; 
    fetch(myUrlAPI, {
      method: "GET",
      headers: {
        "authorization-key": token
      }
    }).then(res => res.json()
    ).then(function(json) {
      this.setState({
          isLoaded: true,
          models: json
        });
    }, function(error) {
      console.log(error)
    })

【讨论】:

    猜你喜欢
    • 2019-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-04
    • 1970-01-01
    • 2017-02-10
    • 2012-01-15
    相关资源
    最近更新 更多