angular - 无法进行第三方 API 请求

标签 angular ionic2 cors

我正在开发一个 Ionic 2 应用程序,它使用来自 Oxford Dictionary 的第三方 API。他们的 API 需要 app_idapp_key 作为身份验证步骤才能工作。

这是对 API 进行 GET 请求调用的服务

@Injectable()
export class OxfordVocabularyService {
  private app_id: any;
  private app_key: any;
  private OxfordBaseRequestURL: any;
  constructor(private http: Http) {
    this.app_id = configuration.oxfordAPI.app_id;
    this.app_key = configuration.oxfordAPI.app_key;
    this.OxfordBaseRequestURL = configuration.oxfordAPI.requestURL;
  }


  public getWordIPA(word: String): Promise<any> {
    let headers = new Headers({ 'Accept': 'application/json' });
    headers.append('app_id', this.app_id);
    headers.append('app_key', this.app_key);
    let options = new RequestOptions({ headers: headers });
    return this.http.get(this.OxfordBaseRequestURL + word + '/pronunciations', options).toPromise().then(response => {
      console.log(response.json());
    });
  }

当应用程序运行服务调用时,它会抛出错误 enter image description here

浏览器上的更多请求信息: enter image description here enter image description here

API 请求在 Postman 上运行良好 enter image description here

我在 header 请求中附加了 app_idapp_key,为什么我会收到错误。

403 - Authentication Parameters missing

这与 CORS 相关吗?你能告诉我正确调用 API 的方法吗?

更新

非常感谢@suraj 和@n00dl3,我通过向 ionic 配置添加代理 解决了这个问题。

ionic.config.json

 "proxies": [
    {
      "path": "/oxfordapi",
      "proxyUrl": "https://od-api.oxforddictionaries.com/api/v1/entries/en"
    }
  ]

并将GET请求路径改为

this.http.get('oxfordapi/' + word + '/pronunciations', options)

最佳答案

Oxford dictionnaries API 似乎不支持 CORS :

Sometimes pre-flight requests will produce the error message “No 'Access-Control-Allow-Origin' header is present on the requested resource.”

Unfortunately, we are unable to support client-side application requests (this includes JavaScript, JScript, VBScript, Java applets, ActionScript, etc.).

This is because our API does not currently support CORS requests due to the potential implications for the security of our server. Instead, we suggest you to make the query reach your server side application, and then send the API request from the server rather than from the client.

source

因此您需要为 ionic serve 创建一个代理(这不会发生在打包的 iOS/Android 应用程序上,因为没有预检请求)。

创建 ionic 代理,参见 this answer

关于angular - 无法进行第三方 API 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43584752/

相关文章:

javascript - 发送前预览图像

angular - 如何在 ngFor 循环中创建变量?

javascript - 在 ionic 2 中等待 foreach 的执行继续下一步

heroku - OPTIONS http 方法在 Heroku 上给出空响应

node.js - Passport js 无法跨域维护 session

javascript - 输入(类型 ="search")十字图标的 Angular 事件绑定(bind)?

angular - 在 Angular 6 中添加加载更多按钮

ionic-framework - ionic 服务/ ionic 运行未反射(reflect)变化

javascript - 从 URI 获取文件 base64

php - 设置 PHPSESSID Cookie、CORS