Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - axios - blocked by CORS policy. How to unblock [duplicate]

I am running a simple API request to return data to a simple API search I've written. I say it's simple API call because there is no authentication needed and I can do it in python very simply.

However, I am having issues when using Axios in React.

Code:

 axios.get('https://www.keyforgegame.com/api/decks/59554ab7-b414-4220-8514-408a0dbf572d')

I've tried looking here and everyone one makes it sound so simple, but I can't seem to do anything. I've tried.

axios.get('https://www.keyforgegame.com/api/decks/59554ab7-b414-4220-8514-408a0dbf572d', { crossDomain: true })

and

axios.get('https://www.keyforgegame.com/api/decks/59554ab7-b414-4220-8514-408a0dbf572d, {
        headers: {
          'Access-Control-Allow-Origin': true,
        },
        })

But I keep getting errors like Access to XMLHttpRequest at 'https://www.keyforgegame.com/api/decks/59554ab7-b414-4220-8514-408a0dbf572d' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

or

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Do I need to put something in the header to make this work? Or is this some kind of setting I need to make in react.

Help!

like image 977
Micah Pearce Avatar asked Dec 23 '18 23:12

Micah Pearce


People also ask

How do you unblock CORS policy in react?

Enable CORS on Server Side Inside the request middleware callback, I first set the Access-Control-Allow-Origin header to an asterisk. The asterisk indicates that this resource can be requested by any client. Let's also change the endpoint in our React app.


1 Answers

You just cannot override CORS check from the client side. Just cannot. CORS is security feature and there would be no sense if it were possible just to disable it.

There are different approaches.

  1. Depending on your words

    I say it's simple API call because there is no authentication needed and I can do it in python very simply.

    I believe you just need to ensure no extra headers are send so request would become simple in meaning of CORS. Across axios site I've found several ways to drop any extra headers for specific request:

    a. either by specifying headers explicitly

    b. or by creating different axios instance that you will not provide with Authorization header or whatever force CORS to be run

  2. making proxy to be run on your domain

  3. making backend to whitelist you domain with listing it in Access-Control-Allow- Origin response header
like image 119
skyboyer Avatar answered Oct 22 '22 12:10

skyboyer