Firebase 获取 - 无访问控制允许来源

Luc*_*ile 10 javascript cors firebase reactjs redux

我正在开发一个应用程序,React + Redux并且我的JSON数据库位于Firebase数据库中。为此,我尝试fetch从一个有效的 URL获取我的数据(从 Firebase 模拟器验证)

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

这将返回给我错误:

Fetch API 无法加载https://console.firebase.google.com/project/****/database/data/**/*/***/*。从'https://console.firebase.google.com/project/重定向/数据库/数据/ ** / / / '到“https://accounts.google.com/ServiceLogin?ltmpl=firebase&osid=1&passive=true... ole.firebase.google.com/project/ /database/data/ / /** / ' 已被 CORS 策略阻止:请求的资源上不存在 'Access-Control-Allow-Origin' 标头。因此,不允许访问 Origin 'null'。如果不透明响应满足您的需求,请将请求的模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。`

我尝试了很多解决方案,比如添加到 fetch 的第二个参数{ mode: 'no-cors', credentials: 'same-origin'},但是当我尝试这个时,我得到Uncaught (in promise) SyntaxError: Unexpected end of input.

我错过了什么?

小智 9

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')
Run Code Online (Sandbox Code Playgroud)


gop*_*ppu -6

对于允许跨域的简单请求,服务器只需要Access-Control-Allow-Origin在响应中添加标头即可。

如果您有任何疑问,另请参阅此教程

跨源 XMLHttpRequest

使用 CORS