2017-10-16 92 views
3

我在尝试对API进行GET调用时遇到了Ionic 3的CORS问题。我正在使用离子本地服务器,在命令行中为活服务器运行离子服务器。IONIC 3 CORS ISSUE

错误 否请求的资源上存在'Access-Control-Allow-Origin'标头。因此不允许访问原产地'http://localhost:8100'。

我试图更新 “ionic.config.json” 使用代理设置,但似乎并不奏效..

{ 
    "name": "projectLeagueApp", 
    "app_id": "47182aef", 
    "type": "ionic-angular", 
    "integrations": { 
    "cordova": {} 
    }, 
    "proxies": [ 
    { 
     "path":"/games", 
     "proxyUrl": "https://api-2445582011268.apicast.io/games/" 
    } 
    ] 
} 

我的数据服务

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) 
    } 

} 

我想拨打电话至此api

请求网址 https://api-2445582011268.apicast.io个 HEADERS 核心价值 用户键YOUR_KEY 接受应用程序/ JSON

的首要问题 我的呼叫失败。如何为这个问题创建代理?

+1

尝试将'http.get'请求中的url更改为'/ games'。代理将用真正的替代它。 – emroussel

回答

0

代理功能期望您引用本地服务器。在您的GET请求中,您仍然指向远程API。如果您将代码更改为this.http.get('/games/...',它应该开始工作,因为请求将转到http://localhost:8100/games...,“代理”选项将捕获并传递到您提供的URL。

您可能也只需要在proxyUrl字段中输入https://api-2445582011268.apicast.io。我认为路径的其余部分是直通。

+0

嘿杰夫, 我做了你问。我将proxyUrl更改为“https://api-2445582011268.apicast.io”,我不再收到CORS问题。 我现在有另一个问题。我收到一个新的错误 - “运行时错误 位置0的JSON中的意外标记H”。我不知道为什么我收到此错误。 –

+0

通过chrome开发工具Network选项卡查看您的请求。什么是HTTP响应代码?你可能会在那里看到更多的信息。另外,不确定是否在控制台中看到任何指示代理正在处理请求的内容。也许有更多的信息。 此外,我建议使用ARC或邮递员或某些REST客户端来打击您的代理服务配置类似于您在网络选项卡中看到的内容。可能更容易在那里调试API调用。 –

2

要解决此问题,请更改以下行

ionic.config.json

{ 
    "name": "projectLeagueApp", 
    "app_id": "47182aef", 
    "type": "ionic-angular", 
    "integrations": { 
    "cordova": {} 
    }, 
    "proxies": [ 
    { 
     "path":"/games", 
     "proxyUrl": "https://api-2445582011268.apicast.io/games" 
    } 
    ] 
} 

您必须删除“/”,这是在“proxyUrl”的结束。

我的数据服务

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) 

在HTTP调用,URL应以“/游戏的开始。 '/ games',因为离子会代理http://localhost:<port>/gameshttps://api-2445582011268.apicast.io/games

请在您的应用程序中使用上述方法进行外部GET和POST调用。

谢谢。

+0

谢谢!这解决了我的问题! –

+0

很高兴帮助。 @ChrisSimmons请注意此答案,以便具有类似查询的开发人员可以从中获得解决方案。 –