-1

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
Tequila
  • 246
  • 1
  • 13
  • Does this answer your question? [Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?](https://stackoverflow.com/questions/20035101/why-does-my-javascript-code-receive-a-no-access-control-allow-origin-header-i) – unicorns4re4live Jan 25 '21 at 08:43

1 Answers1

1

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.

Marwan
  • 388
  • 2
  • 11