首页 > 解决方案 > Angular / API 消耗 - 请求标头 - CORS 代理

问题描述

我被卡住了..请帮忙。

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

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

邮差

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

但我似乎无法使用 Angular 在标题中成功添加 x-api-key。我认为这是因为 CORS 预检,但我几乎可以肯定这不是原因。

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

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

邮递员拦截器

以下是来自 Chrome 控制台的错误:

Chrome 控制台

这是我的 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));
  }
}

角 CLI:7.1.1 节点:11.3.0

标签: angularapicorshttp-headershttprequest

解决方案


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


推荐阅读