Firebase Fetch - No Access-Control-Allow-Origin

Firebase Fetch - No Access-Control-Allow-Origin

本文关键字:Access-Control-Allow-Origin No Fetch Firebase      更新时间:2023-09-26

我正在开发一个应用程序与React + Redux,我有我的JSON数据库内的Firebase DB。要做到这一点,我试图从有效的URL(从Firebase模拟器验证)fetch我的数据

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

返回错误:

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

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

我错过了什么?

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')

我在fetchserviceworker实现中遇到了这个问题

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

使用歌珥。