I'm consuming tone analyser api from IBM Watson tools. As testing it by postman it's working fine, but in Angular it return error as 500 status. As tone analyser api it requires authorization which I put credentials into headers.
Here is sample of my code.
service.ts:
const TONE_API = "https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone?version=2017-09-21&text=";
const httpOptions = {
headers: new Headers({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin':'*',
'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept, Authorization',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Authorization': 'Basic ************************:************'
})
};
const options: RequestOptionsArgs = new RequestOptions();
options.headers = httpOptions.headers;
@Injectable()
export class ToneAnalyserService {
constructor(private http: Http) { }
// API: GET /message
getAnalyser(message:string) {
let url = TONE_API + message;
return this.http.get(url, options)
.map(res => res.json())
.catch(err=>{
throw(err);
});
}
component.ts:
this.message = "I like this idea!";
this.toneAnalyser.getAnalyser(this.message).subscribe(res =>{
this.result = res;
console.log(res.json());
}, err => {
console.log(err);
});
You can't do direct calls to
watsonplatform
from browser application due to CORS.watsonplatform
doesn't support that policy.You have to create your own backend service, which will proxy your requests.
OR:
For local development you can create proxy.config.js alias:
and make calls from application like
get('/watsonplatform/tone-analyzer/api/v3/tone?version=2017-09-21&text=')
When you will host your application use nginx aliases to do the same thing.