angular - 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 控制台的错误:
这是我的 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
解决方案
Content-Type
标头指定您发送到服务器的请求对象的媒体类型。因为您只是从服务器获取 JSON 数据,您应该将Accept
标头设置为您想要的响应类型,即Accept: application/json
.
推荐阅读
- android - Android Fragment 向 Android Activity 添加菜单
- sql-server - 在 SQL Server 中将 NULL 或 0.00 替换为 00.00
- php - Wordpress ACF php 关系
- math - 用 4 个点和指定的坡度角对人工地平进行编码
- spring-boot - springboot 应用程序无法以 classnotfoundexception 启动
- twilio - 为什么 Twilio Studio 中的“发送并等待回复”小部件没有“收件人”字段?
- here-api - 通过 Carthage 作为依赖管理器下载 HERE SDK for iOS (PREMIUM EDITION)
- reactjs - React Hooks addEventListener 未定义
- mql4 - 在 mql4 中处理 json 字符串
- swift - 添加幻灯片动画以更改 UIImageView 的图像