【问题标题】:Firebase Fetch - No Access-Control-Allow-OriginFirebase Fetch - 无访问控制允许来源
【发布时间】:2017-02-26 04:15:26
【问题描述】:

我正在使用React + Redux 开发一个应用程序,并且我的JSON 数据库位于Firebase 数据库中。 为此,我正在尝试从有效的 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 }))
    }

这会返回给我的错误:

Fetch 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”标头。因此,Origin 'null' 不允许访问。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。`

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

我错过了什么?

【问题讨论】:

  • 我遇到了同样的问题,我通过将{ method: 'GET', mode: 'cors', headers: new Headers({ 'Content-Type': 'application/json' } 传递给fetch 作为第二个参数来解决它。

标签: javascript reactjs firebase redux cors


【解决方案1】:

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!

}

【讨论】:

    【解决方案2】:
    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')
    

    【讨论】:

    • 当我在 url 中出现拼写错误时发生这种情况
    • 这有帮助。谢谢你。最后我错过了.json
    • ? 谢谢,“.json”部分是强制性的..
    【解决方案3】:

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

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

    Cross-Origin XMLHttpRequest

    Using CORS.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-12
      • 1970-01-01
      • 1970-01-01
      • 2021-12-03
      • 1970-01-01
      • 2016-01-02
      相关资源
      最近更新 更多