json - IONIC 3 CORS 问题

标签 json angular cors ionic3 angular-services

在尝试对 API 进行 GET 调用时,我遇到了 Ionic 3 的 CORS 问题。我正在使用 Ionic 本地服务器,在实时服务器的命令行中运行 ionic serve。

Error No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.

我尝试使用代理设置更新 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
Key Value
user-key    YOUR_KEY
Accept  application/json

主要问题 我的通话失败。如何为这个问题创建代理?

最佳答案

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

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”开头。 '/games' 因为 ionic 将代理 http://localhost:<port>/gameshttps://api-2445582011268.apicast.io/games

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

谢谢。

关于json - IONIC 3 CORS 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46777212/

相关文章:

android - 如何从网站获取特定数据并将其显示在我的应用程序中?

javascript - 查找使用 vue-cli 生成的 Webpack-simple 和 Vuejs 图像的问题

angular - 修复 EXIF 方向 Angular 2

api - CORS 安全性“Access-Control-Allow-Origin : *“(wildcard)

javascript - $q。所有 promise (访问控制允许来源)

json - 设置或覆盖通用编码对象的属性

javascript - jQuery JSON AJAX 请求不同域

Angular 2 - 存储全局变量(如身份验证 token )以便所有类都可以访问它们的最佳方法是什么?

css - 如何根据字符长度> 128 的条件应用 css 类

javascript - Access-Control-Allow-Origin 不允许 Origin <origin>