【问题标题】:CORS error on production build on device too设备上的生产构建也出现 CORS 错误
【发布时间】:2019-08-28 15:24:18
【问题描述】:

我已经使用这个 CLI 构建了 Ionic 4 应用程序:

ionic cordova build android --prod

service.ts

  get(): Observable<any> {
   return this.http.get("http://api.openweathermap.org/data/2.5/forecast?lat=52.974431&lon=70.2398363&appid=myapi&units=metric");
  }

为什么还是会报 CORS 错误?

访问 XMLHttpRequest 在 'http://api.openweathermap.org/data/2.5/forecast?lat=52.974431&lon=70.2398363&appid=myid&units=metric' 来自原点“http://localhost:8100”已被 CORS 策略阻止: 响应中“Access-Control-Allow-Origin”标头的值 当请求的凭证模式为 '包括'。发起请求的凭证模式 XMLHttpRequest 由 withCredentials 属性控制。

据我所知,它应该在设备上运行而不会出错,不是吗?为什么它仍然在设备上显示http://localhost:8100?根据this doc,它应该可以在设备上正常工作吗?

注意:我使用chrome://inspect/#devices 来获得上述错误?

【问题讨论】:

  • 您的应用程序是否有拦截器在所有请求上添加withCredentials: true 选项?
  • @R.Richards 我在那个页面上有AuthGuard。为什么?
  • 因为错误使您看起来在 HTTP GET 调用期间传递了withCredentials: true,而实际上并不需要。添加选项的拦截器会解释这一点。
  • @R.Richards 好点。但不是我的问题。我稍后会给出完整的答案。谢谢。
  • 如果您有解决方案,请更新它,因为我已经遇到了这种类型的错误,但现在我使用的是 HTTP cordova 插件

标签: angular typescript cors ionic4


【解决方案1】:

最近我遇到了同样的问题,但我通过在 android 和 ios 设备上使用 cordova-plugin-advanced-http 解决了它。

安装

ionic cordova plugin add cordova-plugin-advanced-http
npm install @ionic-native/http

使用

import { HTTP } from '@ionic-native/http/ngx';

constructor(private http: HTTP) {}

...

this.http.get('http://ionic.io', {}, {})
  .then(data => {

    console.log(data.status);
    console.log(data.data); // data received by server
    console.log(data.headers);

  })
  .catch(error => {

    console.log(error.status);
    console.log(error.error); // error message as string
    console.log(error.headers);

  });

更多详情:见official link

【讨论】:

猜你喜欢
  • 2018-12-15
  • 2019-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-25
  • 1970-01-01
  • 1970-01-01
  • 2019-05-03
相关资源
最近更新 更多