10
votes

I'm developing an app with React + Redux and I have my JSON database within a Firebase DB. To do this I'm tryin to fetch my data from a valid URL (validated from Firebase simulator)

let firebase = 'https://******.firebaseio.com/**/*/***/*' 
    return (dispatch) => {
        return fetch(firebase)
            .then(res => res.json())
            .then(json => dispatch({ type: 'GET_JSON', payload: json }))
    }

This returns to me the error:

Fetch API cannot load https://console.firebase.google.com/project/****/database/data/**/*/***/*. Redirect from 'https://console.firebase.google.com/project//database/data/**///' to 'https://accounts.google.com/ServiceLogin?ltmpl=firebase&osid=1&passive=true…ole.firebase.google.com/project//database/data///**/' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' 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've tried many solutions, like adding to fetch's second argument { mode: 'no-cors', credentials: 'same-origin'}, but when I try this i get Uncaught (in promise) SyntaxError: Unexpected end of input.

What am I missing?

3
I had the same problem and I solved it by passing { method: 'GET', mode: 'cors', headers: new Headers({ 'Content-Type': 'application/json' } to fetch as the second argument.U r s u s

3 Answers

9
votes
likely error that arise to  cors blocked when using firebase is
when you initiate a put or get request with an incomplete firebase url
e.g
// wrong form
 this.http.get('https://******.firebaseio.com/data')   //this will throw an exception

// correct form                                                    
  this.http.get('https://******.firebaseio.com/data.json')
-1
votes

I had this problem with a serviceworker implementation of fetch

self.addEventListener('fetch', (e) => {

fetch(e.request) // valid arg && works with firebase

fetch(e.request.url) // valid arg but will cause access-control error!

}
-5
votes

For a simple request to be allowed cross-domain, the server simply needs to add the Access-Control-Allow-Origin header to the response.

Also refer this turorial, if you have any doubts

Cross-Origin XMLHttpRequest

Using CORS.