Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
90 views
in Technique[技术] by (71.8m points)

javascript - Having Api Cors Problems in React

So I am having a problem displaying data from an Api, I am getting this errors 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.and this one xhr.js:177 GET https://swapi.py4e.com/ net::ERR_FAILED and this one createError.js:16 Uncaught (in promise) Error: Network Error at createError (createError.js:16) at XMLHttpRequest.handleError (xhr.js:84) Any help would be highy appriciated

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
question from:https://stackoverflow.com/questions/65881385/having-api-cors-problems-in-react

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Most of the time, you can't just access an API without a specific API key. Every browser natively implements a so-called CORS-policy. What this does, basically, is that it doesn't allow a domain ("https://swapi.py4e.com/" in your case) to be accessed from a different domain or server ("localhost" in your case). This is a security measure.

Publicly accessible API's either generate an API key for you to use, or they allow access from any domain, therefore circumventing the CORS-policy. In both cases, however, the answer lies with the server on "https://swapi.py4e.com/". If you control that server, then you should allow access from you IP-address (or anywhere while developing) and then from the specific domain where your website is hosted (in production). If you don't control the server, then you would need an API key from the people controlling that server or you would have to ask them to grant your server access, by whitelisting your IP-address.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...