首页 > 解决方案 > 获取对我的 React 应用程序的 API 请求

问题描述

我正在尝试调用 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>€&lt;/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>
      );
    }
  }
}

<ul>标签中,我只是想测试json的结果。

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

标签: javascriptreactjsrestapireact-native

解决方案


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

 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)
    })

推荐阅读