使用基本身份验证反应简单的REST API

时间:2020-08-05 11:33:19

标签: reactjs rest

我正在尝试学习如何在休息时使用react并被调试困住,或者至少检查出了什么问题。我一直在按照教程进行操作,只是替换了适合我的示例剩余api响应的值,但页面空白。

我的App.js

 class App extends Component {
      render() {
        return (
          <Products products={this.state.products} />
        )
      }   
      state = {
        products: []
      };

      componentDidMount() {
        var headers = new Headers();
        //test1:test1 is username and password
        headers.append("Content-Type", "application/json");
        headers.append("Authorization", "Basic " + base64.encode("myKey:myPass"));

        fetch('myURL', {headers: headers})
        .then(res => res.json())
        .then((data) => {
          this.setState({ products: data })
        })
        .catch(console.log)
      }

    }

我的products.js

const Products = ({ products }) => {
  return (
    <div>
      <center><h1>Products List</h1></center>
      {products.map((product) => (
        <div class="card">
          <div class="card-body">
            <h5 class="card-title">{product.title}</h5>
            <h6 class="card-subtitle mb-2 text-muted">{product.price}</h6>
            <p class="card-text">{product.id}</p>
          </div>
        </div>
      ))}
    </div>
  )
};

export default Products

我的示例json响应如下:

{
    "products": [
        {
            "title": "Cras Selma dress",
            "id": 4985,            
            "price": "1499",
        },
        {
            "title": "Selected Homme Aron suede jacket",
            "id": 4886,
            "price": "2700",

        }
    ]
}

我的第一个猜测是它没有得到正确的响应或没有处理响应。当我使用基本身份验证通过邮递员检查我的网址时,所有返回的信息都与我发布的json响应类似,都很好。

1 个答案:

答案 0 :(得分:0)

我现在知道您遇到了CORS问题(在问题的评论中进行了讨论)。有几种解决方法,正确的方法取决于您使用的服务器类型。

如果您使用的是 Node.js

app.use(cors())

足够了,了解更多信息:https://expressjs.com/en/resources/middleware/cors.html

除此之外,如果您想快速修复,还有Chrome扩展程序可以帮助您: https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf

因此,问题不在您的代码中,而在CORS中,您可以在此处https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS了解更多信息。

另一种针对CORS的快速解决方案是https://cors-anywhere.herokuapp.com/

您将其附加在实际的API之前,如下所示:

const MY_API = 'http://localhost:8080/api/items';

const FULL_API = `https://cors-anywhere.herokuapp.com/${MY_API}`;

axios.get(FULL_API);

尽管如此,我还是强烈建议您使用谷歌搜索如何解决后端使用的CORS问题。