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

IT技术 javascript reactjs firebase redux cors
2021-05-10 10:45:52

我正在开发一个应用程序,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 }))
    }

这将返回给我错误:

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.

我错过了什么?

3个回答
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')

我在serviceworker实现时遇到了这个问题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!

}

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

如果您有任何疑问,也可以参考此教程

跨域 XMLHttpRequest

使用 CORS