Search code examples
javascriptibm-cloudwatson

Get request to watson tone analyzer api returns No 'Access-Control-Allow-Origin' 401 error


When I do a get request to sent my content to the watson token analyzer api to get the tone analysis json, it returns a 401 No 'Access-Control-Allow-Origin' error. I'm doing this from the client side with javascript.

Is it possible to query the tone analyzer api with a get request from the client side?

Here's what I'm doing:

$.ajax({
    url:'https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone?version=2016-05-19&text='+encodeURI(input),
    data:{
        'username':'password'
    },
    contentType:'application/json',
    method:'GET',
    success:function(tone){
        console.log(tone);
    }
});

Requesting token client side to use api client side:

$.ajax({
    url:'https://gateway.watsonplatform.net/authorization/api/v1/token',
    data:{
        'url':'https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone',
        'username':'password'
    },
    dataType:'jsonp',
    contentType:'application/javascript',
    method:'GET'
});

Solution

  • Looks like Tone Analyzer is CORS supported which allows for option #2 below

    You can either:

    1. Use the API server side
    2. Get an authentication token (expires after 1 hour) on your server side using the authorization service. Return that token to your client so your javascript call can use the token when it requests the Tone Analyzer API from your client.

    An example for #2 above is here