我想从 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 应用程序有什么问题。
提前致谢。