消耗Angular / API-请求标头-CORS代理

时间:2018-12-13 14:31:54

标签: angular api cors http-headers httprequest

我被困住了。请帮助。

我正在尝试从API提取数据(该API已经设置)。

使用Postman时,我可以成功获取数据。我只是将x-api-key添加为标题。

Postman

我需要发送GET请求,每个请求必须在http请求标头中包含一个私有API密钥,如以下示例所示:x-api-key:TcKkYuizu67bsamplexeF4AGTnGWgY7E8MCiTEST

但是我似乎无法使用Angular在标头中成功添加x-api-key。我以为那是因为CORS的飞行前,但是我几乎可以肯定这不是原因。

我添加了CORS转换器和Postman Interceptor扩展。

使用Postman Interceptor扩展程序,我注意到有些不对劲。 x-api-key根本没有归类为标头,并且找不到密钥本身:

Postman Interceptor

这是Chrome控制台中的错误:

Chrome Console

这是我的app.component.ts代码:

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    'x-api-key': 'PE84t4CCUC5e7JaGqSeyH7WdRfU6rhoRa6*****',
    'Authorization': 'x-api-key PE84t4CCUC5e7JaGqSeyH7WdRfU6rhoRa6*****'
  })
};

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'API';

  constructor(private http: HttpClient) {
    console.log('test');
  }
  ngOnInit(){
    let obs = this.http.get('https://api-proxy.***/GetChannels', httpOptions);
    obs.subscribe((response) => console.log(response));
  }
}

Angular CLI:7.1.1 节点:11.3.0

2 个答案:

答案 0 :(得分:1)

Content-Type标头指定要发送到服务器的请求对象的媒体类型。因为您只是从服务器获取JSON数据,所以应将Accept标头设置为所需的响应类型,即Accept: application/json

答案 1 :(得分:1)

x-api-key不是CORS safelisted request header。它将触发一个OPTIONS请求,该请求必须具有成功的响应,否则XHR将被浏览器阻止。

chrome插件无法基于当前chrome扩展API修改响应HTTP状态代码。解决方案是使用CORS proxy来正确响应OPTIONS请求。有关更多信息,请参见Disable same origin policy in Chrome