设备上的生产构建也出现 CORS 错误
CORS error on production build on device too
我已经使用此 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错误?
Access to XMLHttpRequest at
'http://api.openweathermap.org/data/2.5/forecast?lat=52.974431&lon=70.2398363&appid=myid&units=metric'
from origin 'http://localhost:8100' has been blocked by CORS policy:
The value of the 'Access-Control-Allow-Origin' header in the response
must not be the wildcard '*' when the request's credentials mode is
'include'. The credentials mode of requests initiated by the
XMLHttpRequest is controlled by the withCredentials attribute.
据我所知,它应该 运行 在设备上没有错误不是吗?为什么它仍然在设备上显示 http://localhost:8100
?根据 this doc 它应该可以在设备上正常工作 no?
注:我用chrome://inspect/#devices
得到上面的错误?
最近我遇到了同样的问题,但我通过对 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
我已经使用此 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错误?
Access to XMLHttpRequest at 'http://api.openweathermap.org/data/2.5/forecast?lat=52.974431&lon=70.2398363&appid=myid&units=metric' from origin 'http://localhost:8100' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
据我所知,它应该 运行 在设备上没有错误不是吗?为什么它仍然在设备上显示 http://localhost:8100
?根据 this doc 它应该可以在设备上正常工作 no?
注:我用chrome://inspect/#devices
得到上面的错误?
最近我遇到了同样的问题,但我通过对 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