代码之家  ›  专栏  ›  技术社区  ›  Niral Munjariya

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

  •  0
  • Niral Munjariya  · 技术社区  · 7 年前

    我想从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 -u "{username}":"{password}" "https://gateway.watsonplatform.net/conversation/api/v1/{method}"
    

    如果我添加以下内容,上述请求可以正常工作 Allow-Control-Allow-Origin: * chrome中的扩展,因此无法理解Angular应用程序有什么问题。

    提前谢谢。

    1 回复  |  直到 7 年前
        1
  •  0
  •   Niral Munjariya    7 年前

    我已经解决了问题,它是从服务器端,访问控制允许头没有正确设置从服务器端

    我试图设置“授权”标题,但它没有列在“访问控制允许标题”中,这就是浏览器出现错误的原因。

    在飞行前请求中,浏览器只允许您添加“Access Control allow headers”(访问控制允许标头)中列出的客户端标头(在我的情况下是角度标头)。