【问题标题】:Having Api Cors Problems in React在 React 中遇到 Api Cors 问题
【发布时间】:2021-01-25 08:39:54
【问题描述】:

所以我在显示来自 Api 的数据时遇到问题,我收到了这个错误 Access to XMLHttpRequest at 'https://swapi.py4e.com/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.还有这个 xhr.js:177 GET https://swapi.py4e.com/ net::ERR_FAILED 和这个createError.js:16 Uncaught (in promise) Error: Network Error at createError (createError.js:16) at XMLHttpRequest.handleError (xhr.js:84) 任何帮助都会受到高度重视

import React,{useEffect, useState}from 'react'
import axios from 'axios';

function Home() {

    const [data, setData] =  useState([]);
    const apiURL = "https://swapi.py4e.com/";
    const fetchData = async () => {
        const response = await axios.get(apiURL)
        setData(response.data) 
    }
    return (
        <div >
          <button onClick={fetchData}></button>
        </div>
    )
}
export default Home

【问题讨论】:

标签: javascript reactjs api


【解决方案1】:

大多数时候,您不能只访问没有特定 API 密钥的 API。每个浏览器本身都实现了一个所谓的CORS-policy。基本上,它的作用是不允许从不同的域或服务器(在您的情况下为“localhost”)访问域(在您的情况下为“https://swapi.py4e.com/”)。这是一项安全措施。

可公开访问的 API 要么生成供您使用的 API 密钥,要么允许从任何域访问,从而规避 CORS 政策。然而,在这两种情况下,答案都在于“https://swapi.py4e.com/”上的服务器。如果您控制该服务器,那么您应该允许从您的 IP 地址(或开发时的任何地方)访问,然后从您的网站托管的特定域(在生产中)访问。如果您不控制服务器,那么您需要来自控制该服务器的人员的 API 密钥,或者您必须要求他们通过将您的 IP 地址列入白名单来授予您的服务器访问权限。

【讨论】:

    猜你喜欢
    • 2020-10-20
    • 2022-01-26
    • 2015-02-24
    • 2021-04-06
    • 2019-03-26
    • 2020-10-29
    • 2021-11-21
    • 1970-01-01
    • 2018-07-19
    相关资源
    最近更新 更多