【发布时间】:2022-01-28 12:22:16
【问题描述】:
我想从外部 api 获取数据,但由于 cors 政策而被阻止,我无法在服务器端修改标头。
我找到了一些解决方案,但对我不起作用,其中一个是使用 chrome 扩展,但是当我在我的设备上运行应用程序时,我遇到了同样的错误
错误信息:
从源“http://localhost:8100”访问“URL”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应不 通过访问控制检查:没有“Access-Control-Allow-Origin”标头 出现在请求的资源上。
这是我的代码:
const url = 'http://host.com:port_number/get.php';
let headers=new HttpHeaders({
'Access-Control-Allow-Headers': 'Accept,X-Custom-Header',
'Access-Control-Allow-Origin':'*',
'Access-Control-Allow-Credentials':'true'
});
return this.http.get(url, {headers:headers, params: new HttpParams().set('username', this.log).set('password', this.pass), responseType: 'text' ,observe: 'response'}).subscribe(
data => {
console.log(data);
},
error => console.error(error),
() => {
});
【问题讨论】:
-
所以您想绕过无法从客户端控制的服务器的 CORS 策略?
-
是的,没错,所有者想要更新他的应用程序,它是用 Java 开发的,他们没有这个错误,但现在我想用 ionic 创建一个,但我卡住了