邮递员给出回应,但 ReactJS 代码抛出错误

Postman gives response but ReactJS code throws error

我正在尝试从 API 中获取记录,但是当我使用以下代码时它 returns 不成功响应。但与此同时,它在邮递员中用状态码 200 给我正确的回应。这是我的代码。请帮助:

import React, {Component} from "react";

    const urlEndPoint = myEndPoint => "https://api.github.com/users/adhishlal"

    export default class Categories extends Component {
     constructor(props) {
       super(props)
       this.state = {
          requestFailed: false
       }
     }

    componentDidMount() {


       fetch(urlEndPoint(this.props.myEndPoint))


         .then(response => {
           if (!response.ok) {
             throw Error(response.statusText)
           }
           return response
         })

         .then(d => response.json())


         .then(response => {
           this.setState({
             responseData: d
           })
         }, () =>
         {
           this.setState({
             requestFailed: true
           })
         })


     }

    render() {

    //If request is failed
    if(this.state.requestFailed)
    {
      return <div>Request Failed</div>
    }

    //Waiting for data to load from Zoho
    if(!this.state.responseData)
    {
      return <div>Loading...</div>
    }

    //Finally populate the data when loaded


    var indents = [];
    for (var i = 0; i < 10; i++) {

     indents.push(

      <div className="col-sm-4 col-xs-12"><div className="cr-openings">
      <p className="no-margin font-color-lightGrey no-of-openings">{i+1}</p><p className="catg-openings font-color-white">{this.state.responseData.name}</p>
      <p className="font-color-lightGrey city-openings no-margin">Bangalore , Chennai , Delhi NCR , Hyderabad , Mumbai</p>
    </div>
    </div>

      );
    }


    return (
      <section className="dotted">
          <div className="dotted-bg-dark">
            <div className="container padding-80-0">
              <div className="row m-b-30">
                {indents}
                </div>
              </div>
          </div>
      </section>
    );






    }
    }

你能指出我哪里出错了吗?您可以 运行 在您的 restclient 或 postman 中 API 来查看回复。

我还没有完成您的代码,但会向您展示如何使用 fetch 获取数据。

     fetch('https://api.github.com/users/adhishlal')
     .then(response => {
       response.json().then(function(data){
         console.log(data);
       })

代码中的data就是您需要的数据。

The response of a fetch() request is a Stream object, which means that when we call the json() method, a Promise is returned since the reading of the stream will happen asynchronously.

在我看来,使用 axios 会让生活变得更轻松。

希望对您有所帮助

上面写的代码错误很少。在某些地方返回了不正确的值。同样,setState 是为错误的变量完成的。修复这些问题会使 运行 正常。

我已经更新了导致问题的代码

.then(d => d.json())  //Return d.json() and not response.json()
   .then(response => {
      this.setState({
        responseData: response, //setState to response and not d
      })
   }, () =>