![](/img/trans.png)
[英]Unable to get a token from different Angular project url on a cors enabled .net 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.