Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch API cannot load, cors

In my React app I am trying to make a GET request from my heroku server to get a list of users:

https://blablabla.heroku.com/users

using the following request:

const sendSearch = fetch('/https://blablabla.heroku.com/users', {credentials: 'same-origin'})

function loadMyUsers(data) {
  data.json().then((jsonData) => {
    // console.log(jsonData)

  })
}

sendSearch.then(loadMyUsers)}

However I get the following error:

Fetch API cannot load https://blablabla.heroku.com/users.
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:8080' is therefore not allowed
access. If an opaque response serves your needs, set the request's mode
to 'no-cors' to fetch the resource with CORS disabled.

I tried changing my Fetch method to many things similar to:

const sendSearch = fetch('https://blablabla.heroku.com/users',{
  method: 'GET',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'mode': 'no-cors'
  }
})

but the problem persists.

How do I make the cross domain request?

like image 534
user2456977 Avatar asked Oct 30 '22 11:10

user2456977


1 Answers

On your heroku server you should add Access-Control-Allow-Origin: * to your response headers, or more specific Access-Control-Allow-Origin: http://localhost:8080 if you wish.

On your production server though, you probably won't need this header, unless you have very good reason for cross origin requests.

like image 184
Borna Avatar answered Nov 25 '22 22:11

Borna