0

I'm trying to fetch my data from a heroku app into Redux, but I think I'm running into a CORS issue. I've been playing with "headers" for a while and still can't figure it out.

This is the exact error: "Failed to load https://name-app.herokuapp.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:3000' 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."

And this is my code:

 export function fetchMicros() {
  return dispatch => {
    const url = "https://name-app.herokuapp.com/users";
      return fetch(url, {
       method: 'GET',
       mode: 'cors',
       headers: { 'Content-Type': 'text' },
     })
     .then(handleErrors)
     .then(res => res.json())
     .then(micros => {
        dispatch(fetchVitamins(micros));
     }
   )};
};
John White
  • 121
  • 4
  • 20

1 Answers1

0

If you don't have to do any authentication nor need to pass any data, you can do a no-cors request (more information on mdn page).

fetch(url, {
   mode: 'no-cors',
 })

If you do need cookies or some kind of authentication, then you need to make the server accept your domain and request methods on the preflight response.

In the event that you don't have access to change that on the server, you can create a nodejs server that will handle the calls for you, bypassing any cors checks (only browser cares about cors, servers don't).

Sergio Moura
  • 4,888
  • 1
  • 21
  • 38
  • i do this and i get thrown an error from my `handleErrors` function – John White Jun 13 '18 at 16:58
  • Can you access the url on the browser directly? What does the error says? – Sergio Moura Jun 13 '18 at 16:59
  • Yes i can access it directly. The error throws the catch error function i have `function handleErrors(response) if (!response.ok) { throw Error(response.statusText); } return response; }` – John White Jun 13 '18 at 17:18
  • Using `mode: 'no-cors'` prevents your frontend JavaScript code from having any access to the response body or response headers. See the answer at https://stackoverflow.com/a/43319482/441757 – sideshowbarker Jun 13 '18 at 22:46