userden
userden

Reputation: 1693

'Access-Control-Allow-Origin' error when getting data from the API with Axios (React)

I'm getting an a "XMLHttpRequest cannot load https://example.com. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access."

This is my componenDidMount(), and I'm using axios to get the data from my API.

componentDidMount() {
   this.serverRequest = axios.get(this.props.source).then(event =>{    
     this.setState({
          title: event.data[0].name
      });
   });
}

I'm using "python -m SimpleHTTPServer" on the terminal, to run 'http://localhost:8000'.

I'm using the Chrome browser, and if I turn on the Chrome CORS plugin (to enable cross origin resource sharing), the app works, and I see data displayed from the API on the DOM. But I know that using the CORS plugin is bad, so how should I fix the 'Access-Control-Allow-Origin' error officially?

With Axios, can I somehow add dataType: "jsonp", if that would fix it?

Upvotes: 1

Views: 1323

Answers (1)

Pranesh Ravi
Pranesh Ravi

Reputation: 19133

This is a restriction made by the browser for security reasons when you try to access content in some domain from another domain. You overcome this, you need to set the following in your header

Access-Control-Request-Method
Access-Control-Request-Headers

Many sites restrict CORS. The best way to achieve your goal is to make your python server as a proxy. See the example.

//Request from the client/browser

http://localhost:8000/loadsite?q=https%3A%2F%2Fexample.com

//In your server

 1. Handle the request
 2. Get the query param(url of the website)
 3. Fetch it using your python server
 4. Return the fetching data to the client.

This should work.

Upvotes: 1

Related Questions