I want to call Watson conversation API from the Angular 5 application and for that, I'm using 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:
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.
Sample cURL request:
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.
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.
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.
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'.