5

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?

user2456977
  • 3,830
  • 14
  • 48
  • 87
  • 6
    You have to set the correct `Access-Control-Allow-Origin` headers on your backend. The fetch request seems to work. – Fabian Schultz Mar 05 '17 at 15:56
  • The problem is not with your front-end, as @Borma answered below, but with your server. You have to enable CORS on server-side – Raul Rene May 25 '18 at 13:29

1 Answers1

2

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.

Borna
  • 126
  • 1
  • 7