【发布时间】:2023-03-05 19:22:01
【问题描述】:
我正在开发一个 Angular 5 的 Ionic 应用程序,我使用命令 ionic serve -l 在 localhost 中运行它
我有一个外部网站https://example.com/api?req1=foo&req2=bar的接听电话
但我收到 CORS 被拒绝消息并且没有响应。
无法加载 https://example.com/api?req1=foo&req2=bar:从“https://example.com/api?req1=foo&req2=bar”重定向到“http://example.com/api?req1=foo&req2=bar”已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此不允许访问 Origin 'http://localhost:8100'。
请求代码很简单:
getSomethingList(req1: number, req2: number): Observable<Item[]> {
const requestUrl = 'https://example.com/api?req1=foo&req2=bar';
return this._http.get(requestUrl).map((res: Response) => res.json());
}
我尝试安装 chrome 扩展程序 Moesif Origin & CORS changer 我激活了它并将原点设置在 http://localhost:8100/ (运行我的 ionic 应用程序的位置)。仍然没有结果,但现在我没有看到被拒绝的 CORS 错误,我根本看不到任何错误。
我尝试了代理:
// file ionic.config.json
{
"name": "movielovers",
"app_id": "",
"type": "ionic-angular",
"integrations": {
"cordova": {}
},
"proxies": [{
"path": "/api",
"proxyUrl": "https://example.com/api"
}]
}
然后把const requestUrl = 'https://example.com/api?req1=foo&req2=bar'改成const requestUrl = '/api?req1=foo&req2=bar',我还是不知道这个是干什么用的,对我来说没有意义,但是看了一些教程就明白了。
这样显然,我得到了错误:
GET http://localhost:8100/api?req1=foo&req2=bar 404(未找到)
我尝试安装 nom corsproxy: npm install -g corsproxy 并在命令行中运行 corsproxy。这将在端口中启动服务器。但这行不通。我什至尝试将 corsproxy 与 ionic.config.json 文件中的代理混合,但没有办法。永远得不到答案。
最后我尝试了 jsonp:
首先我在 app.module.ts 中
import { JsonpModule } from '@angular/http';并在导入中声明 JsonpModule。然后在我有请求的提供程序中注入 Jsonp 库
constructor(private jsonp: Jsonp) {}我在请求url末尾添加回调:
const requestUrl = 'https://example.com/api?req1=foo&req2=bar&callback=JSONP_CALLBACK'更改请求方法: return this.jsonp.request(requestUrl).map((res: Response) => res.json());
使用 jsonp,控制台中的错误是:
Uncaught SyntaxError: Unexpected token :
我不知道还能尝试什么,由于 CORS,我无法得到任何响应。我请求的api不受限制,响应邮递员,甚至直接在浏览器中写请求url。但是当从 localhost 运行时,它显然被阻止了,我无法克服它,我失去了很多时间来试图得到响应。我需要一些帮助。
- 离子:3.20.0
- 科尔多瓦
- Angular CLI:1.7.3
- 节点:8.9.4
仅供参考:我使用的 api 是 https://www.comicvine.com/api
编辑: 安装了cordova-plugin-whitelist
将<meta http-equiv="Content-Security-Policy" content="script-src * 'unsafe-inline' 'unsafe-eval'"> 添加到 www/index.html
文件 config.xml 有以下几行:
<content src="index.html" />
<access origin="*" />
<allow-intent href="http://*/*" />
<allow-intent href="https://*/*" />
<allow-navigation href="*" />
【问题讨论】:
标签: angular ionic-framework cors