繁体   English   中英

使用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并返回响应,但是返回如下错误:

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

我试图设置“授权”标头,但未在“ Access-Control-Allow-Headers”中列出,这就是浏览器给出错误的原因。

在预检请求中,浏览器将仅允许您从“ Access-Control-Allow-Headers”中列出的客户端(在我的情况下为Angular)中添加这些标头。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM