json 离子 3 CORS 问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46777212/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
IONIC 3 CORS ISSUE
提问by Chris Simmons
I am having a CORSissue with Ionic 3 when attempting to make GETcalls to an API. I am using Ionic local server, running ionic serve in the command line for live server.
我在尝试调用 API时遇到了 Ionic 3的CORS问题GET。我正在使用 Ionic 本地服务器,在实时服务器的命令行中运行 ionic serve。
ErrorNo
'Access-Control-Allow-Origin'header is present on the requested resource. Origin'http://localhost:8100'is therefore not allowed access.
错误
'Access-Control-Allow-Origin'请求的资源上不存在标头。'http://localhost:8100'因此不允许访问Origin 。
I tried updating ionic.config.jsonwith proxy setting but that does not seem to be working..
我尝试ionic.config.json使用代理设置进行更新,但这似乎不起作用..
{
"name": "projectLeagueApp",
"app_id": "47182aef",
"type": "ionic-angular",
"integrations": {
"cordova": {}
},
"proxies": [
{
"path":"/games",
"proxyUrl": "https://api-2445582011268.apicast.io/games/"
}
]
}
My Data Service
我的数据服务
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class DataProvider {
headers = new Headers({'user-key': '1234567890123'});
options = new RequestOptions ({headers: this.headers});
limit: number = 50;
constructor(public http: Http) {
console.log('Hello DataProvider Provider');
}
getGames(genre, offset_num) {
let genre_id = genre;
let offset = offset_num;
return this.http.get('https://api-2445582011268.apicast.io/games/?fields=name,release_dates,screenshots&limit='+this.limit+'&offset='+offset+'&order=release_dates.date:desc&filter[genres][eq]='+genre_id+'&filter[screenshots][exists]', this.options)
}
}
I am trying to make calls to this api
我正在尝试调用此 api
Request Url
请求网址
https://api-2445582011268.apicast.io
HEADERS
Key Value
user-key YOUR_KEY
Accept application/json
Primary QuestionMy calls are failing. How do I create proxy for this issue?
主要问题我的通话失败。如何为这个问题创建代理?
回答by Alvin Chettiar
To fix this issue, please change the following lines
要解决此问题,请更改以下几行
ionic.config.json
ionic.config.json
{
"name": "projectLeagueApp",
"app_id": "47182aef",
"type": "ionic-angular",
"integrations": {
"cordova": {}
},
"proxies": [
{
"path":"/games",
"proxyUrl": "https://api-2445582011268.apicast.io/games"
}
]
}
You have to remove the " / " which is at the end of of "proxyUrl".
您必须删除“proxyUrl”末尾的“/”。
My Data Service
我的数据服务
return this.http.get('/games/?fields=name,release_dates,screenshots&limit='+this.limit+'&offset='+offset+'&order=release_dates.date:desc&filter[genres][eq]='+genre_id+'&filter[screenshots][exists]', this.options)
In the http call, the url should begin with '/games'. '/games' because ionic will proxy http://localhost:<port>/gamesto https://api-2445582011268.apicast.io/games
在 http 调用中,网址应以“/games”开头。'/games' 因为 ionic 将代理http://localhost:<port>/games到https://api-2445582011268.apicast.io/games
Please use the above method for external GET and POST calls in your application.
请在您的应用程序中对外部 GET 和 POST 调用使用上述方法。
Thank you.
谢谢你。
回答by Saurabh Ahuja
If you wan to use for testing in Chrome just install chrome extension Allow control originQuick and easy way
如果您想在 Chrome 中用于测试,只需安装 chrome 扩展程序 允许控制源快速简便的方法
回答by Raghav Dinesh
To test in development environment, you can run Google Chrome in disable-web-securitymode.
要在开发环境中进行测试,您可以在disable-web-security模式下运行 Google Chrome 。
Steps to follow (On Windows)
要遵循的步骤(在 Windows 上)
- Press WindowsKey + Rto open Run window.
- Enter/input following command and press Enterkey.
- 按Windows+R键打开运行窗口。
- 输入/输入以下命令并按Enter键。
chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security
chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security
Steps to follow (On Ubuntu)
要遵循的步骤(在 Ubuntu 上)
- Kill all the
chrome.exeinstances before you run/execute it.
chrome.exe在运行/执行它之前杀死所有实例。
chromium-browser --disable-web-security --user-data-dir="[some directory here]"
chromium-browser --disable-web-security --user-data-dir="[some directory here]"
- Before Chrome 48
- 在 Chrome 48 之前
chromium-browser --disable-web-security
chromium-browser --disable-web-security
Steps to follow (On Mac)
要遵循的步骤(在 Mac 上)
- Run following command in terminal.
- 在终端中运行以下命令。
open -n -a "Google Chrome" --args --user-data-dir=/tmp/temp_chrome_user_data_dir http://localhost:8100/ --disable-web-security
open -n -a "Google Chrome" --args --user-data-dir=/tmp/temp_chrome_user_data_dir http://localhost:8100/ --disable-web-security
回答by tuhin kole
export function getAuthHttp(http: Http, options: RequestOptions) { console.log("token",storage.get('id_token'));
导出函数 getAuthHttp(http: Http, options: RequestOptions) { console.log("token",storage.get('id_token'));
return new AuthHttp(new AuthConfig({
返回新的 AuthHttp(new AuthConfig({
headerName: 'Authorization',
headerPrefix: 'bearer',
tokenName: 'id_token',
tokenGetter: (() => storage.get('id_token')),
noJwtError: true,
//globalHeaders: [{'Accept': 'application/json'}],
globalHeaders: [{'Content-Type':'application/json'},{"Access-Control-Allow-Origin": "*"}],
}), http, options);
}
}
回答by pawan vedak
My CORSissue got FIXEDwhen I updated Android System Webviewfrom the play store. I tried Cordova-Advance-HTTPPlugin but my PUT Request was not workingwith Cordova-Advance-HTTPplugin.
当我从 Play 商店更新Android System Webview时,我的CORS问题得到了修复。我尝试了Cordova-Advance-HTTP插件,但我的PUT 请求不适用于Cordova-Advance-HTTP插件。
After Updating Android System WebviewI used HTTP Clientplugin which I was using before. Updating Android System Webviewhelped mein CORS issue
更新Android 系统 Webview后,我使用了之前使用的HTTP 客户端插件。更新Android 系统 Webview帮助我解决CORS 问题
回答by Jeff Woodard
the proxy functionality expects that you're referencing the local server. in your GET request, you're still pointed at the remote API. If you change your code to this.http.get('/games/...'it should start to function as the request will go to http://localhost:8100/games..., which the "proxy" option will catch and pass on to the URL you've provided.
代理功能要求您引用本地服务器。在您的 GET 请求中,您仍然指向远程 API。如果您将代码更改为this.http.get('/games/...'它应该开始运行,因为请求将转到http://localhost:8100/games...,“代理”选项将捕获并传递到您提供的 URL。
You may also only need to put https://api-2445582011268.apicast.ioin the proxyUrlfield. I think the rest of the path is passthrough.
你也可能只需要投入https://api-2445582011268.apicast.io的proxyUrl领域。我认为其余的路径是直通的。
回答by Musab
You can handle the CORS when debugging in browser by using CORS extension or by disabling the security of Chrome. But you need to handle the CORS when you debug in app on the server side, I was consuming woo-commerce API ,so i edited it as follows->
您可以在浏览器中调试时通过使用 CORS 扩展或禁用 Chrome 的安全性来处理 CORS。但是当您在服务器端的应用程序中调试时需要处理 CORS,我正在使用 woo-commerce API,因此我对其进行了如下编辑->
1.Plugins->editor->woocomerceapi
1.Plugins->editor->woocomerceapi
right after
紧接着
<?php**
header(“Access-Control-Allow-Origin: *”);
2.Update File
2.更新文件

