简体   繁体   English

使用Angular 5应用程序无法从启用了CORS的API获取响应

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

I want to call Watson conversation API from the Angular 5 application and for that, I'm using Angular HttpClient. 我想从Angular 5应用程序调用Watson对话API,为此,我正在使用Angular HttpClient。

Below is the code snippet: 下面是代码片段:

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);
  });

It should call the API and return the response but it returns an error as below: 它应该调用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.

The request works perfectly with Postman and Node.js request package but not working with the Angular 5 app. 该请求可与Postman和Node.js请求包完美配合,但不适用于Angular 5应用。

Sample cURL request: 样本cURL请求:

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

Above request works fine if I add Allow-Control-Allow-Origin: * extension in the chrome, so unable to understand what's the problem with the Angular app. 如果我在Chrome中添加Allow-Control-Allow-Origin:*扩展名,则上述请求可以正常工作,因此无法理解Angular应用程序的问题。

Thanks in advance. 提前致谢。

I've figured out the problem, it is from the server side, Access-Control-Allow-Headers are not properly set from the server side . 我已经解决了问题,这是从服务器端开始的,从服务器端未正确设置Access-Control-Allow-Headers

I was trying to set 'Authorization' header but it wasn't listed in the 'Access-Control-Allow-Headers' and that's why browser was giving the error. 我试图设置“授权”标头,但未在“ Access-Control-Allow-Headers”中列出,这就是浏览器给出错误的原因。

In the preflight request, the browser will only allow you to add those headers from the client-side(which is Angular in my case) that are listed in the 'Access-Control-Allow-Headers'. 在预检请求中,浏览器将仅允许您从“ Access-Control-Allow-Headers”中列出的客户端(在我的情况下为Angular)中添加这些标头。

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

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