【问题标题】:Ionic 2 app CORS error while using AngularFire2 and Firebase 3使用 AngularFire2 和 Firebase 3 时出现 Ionic 2 应用 CORS 错误
【发布时间】:2026-01-06 15:25:01
【问题描述】:

我正在尝试在我的 Ionic 2 应用程序中使用 AngularFire2 插件来使用自定义令牌对 Google api 进行授权,同时在我的计算机上的 Chrome 中进行开发。它可以在我的 Android 手机上正常测试,请求有效,一切正常。但我试图让它在我的开发环境中也能工作。

我在 Chrome 中运行我的应用时遇到的错误是(我删除了我的密钥):

OPTIONS https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyCustomToken?key=<mykey> 
XMLHttpRequest cannot load https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyCustomToken?key=<mykey>. Response for preflight has invalid HTTP status code 404

告诉我在向 Google 服务器发出选项预请求时遇到问题。问题是我已经安装了 Chrome 插件 Allow-Control-Allow-Origin:* 并在 Chrome 启动时添加了“--disable-web-security”参数。对于该特定请求,它适用于其他服务,但不适用于 AngularFire2。

我发现有人遇到同样的问题,建议切换到 Firefox,但我不会这样做,因为它会破坏其他插件,例如 SQLight 存储。 有没有办法让它在 Chrome 浏览器中工作?

【问题讨论】:

    标签: android google-chrome cors ionic2 angularfire2


    【解决方案1】:

    您可以为您的 CORS 请求添加中间服务器,这将使您的 HTTP 请求使用 CORS 预检并返回结果,仅适用于开发模式。我在我的一个项目中使用了这种方法,因为我只有一个客户端。

    所以你可以这样做:

    getMyInfo(info: Info, provider?: string) {
       if (!provider) {
           provider = 'corsanywhere';
       }
    
    
    
       this.crossGet(`http://google_apis/${Info}/`,`${provider}`).map(res => res.json())
                        .subscribe(res => {
            // GOT RESULT
            console.log("Res: " + res);
       });
    }
    

    这些是您可以使用的提供程序:

    corsanywhere(url: string, options: any): any {
            var promise = this.http.get('https://cors-anywhere.herokuapp.com/' + url);
        return promise;
    };
    
    corsnow(url: string, options: any): any {
        var promise = this.http.get('https://cors.now.sh/' + url);
        return promise;
    };
    
    crossGet(url: string, provider: any, options?: any): any {
        var promise = this[provider](url, options);
        return promise;
    };
    

    事实上,在这种方法中我们并没有解决问题,我们只是覆盖它。但我认为这是一个很好的解决方案,因为您只会将它用于开发。

    希望对你有帮助,祝你好运!

    【讨论】: