无法使用 Angular 5 应用程序从已启用 CORS API 获得响应

Unable to get response from CORS enabled API using the Angular 5 application

我想从 Angular 5 应用程序调用 Watson 对话 API,为此,我正在使用 Angular HttpClient。

下面是代码片段:

import { HttpClient, HttpHeaders } from '@angular/common/http';
const url = 'https://gateway.watsonplatform.net/conversation/api?version=2017-05-26';
const username = 'my-username';
const password = 'secret';
const headers = new HttpHeaders({
  Authorization: 'Basic ' + btoa(`${username}:${password}`)
});
this.httpClient.get('https://gateway.watsonplatform.net/conversation/api?version=2017-05-26', { headers: headers })
  .subscribe(res => {
    console.log(res);
  });

它应该调用 API 和 return 响应,但它 return 是一个错误,如下所示:

Failed to load https://gateway.watsonplatform.net/conversation/api?version=2017-05-26: Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.

该请求与 Postman 和 Node.js 请求包完美配合,但不适用于 Angular 5 应用程序。

示例 cURL 请求:

curl -u "{username}":"{password}" "https://gateway.watsonplatform.net/conversation/api/v1/{method}"

如果我在 chrome 中添加 Allow-Control-Allow-Origin: * 扩展,上述请求工作正常,因此无法理解 Angular 应用程序的问题所在。

提前致谢。

我已经找到问题了,是服务器端的问题,Access-Control-Allow-Headers 没有从服务器端正确设置

我试图设置 'Authorization' header 但它没有在 'Access-Control-Allow-Headers' 中列出,这就是浏览器给出错误的原因。

在预检请求中,浏览器将只允许您添加来自 client-side(在我的例子中是 Angular)的那些 header,它们在 'Access-Control-Allow-Headers'.