I've already gotten a token on the server side and stored it in a cookie, but I can't seem to figure out why I'm getting an error when I query the api with that token.
Here's the jQuery ajax request I'm sending:
$.ajax({
url:'https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone',
data:{
'X-Watson-Authorization-Token':readCookie('token'),
'text':input,
'version':'v3',
'version_date':'2016-05-19'
},
dataType:'jsonp',
contentType:'application/json',
method:'GET',
success:function(tone){
console.log(tone);
}
});
If I don't use dataType:jsonp
, I get a no access control-origin error. When I don't use contentType:application/json
or use contentType:application/javascript
, I get a login dialog when the api is queried asking for a username and password. But I shouldn't have to pass the username and password now that I've got a token. And when I run it this way, with both dataType and contentType, I get a 400 error bad request.
Does anyone know what I am doing wrong? The documentation says I can use the token on the client side., but I have to fetch it on the server side.
UPDATE:
As per advice, I am not accessing the server side code through a jquery ajax call of a separate php file. I am able to get the token, but when I pass it to the api call to the tone analyzer, I get a 400 error. Regardless if I decodeURI the token or not.
Here is my jquery:
$.when($.ajax({
url:'watsonToken.php',
type:'GET',
})).done(function(token){
console.log('watsonToken, lasts 1 hour: ', decodeURI(token));
$.ajax({
url:'https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone',
type:'POST',
data:JSON.stringify({
'body':input,
'version':'2016-05-19'
}),
contentType:'application/json',
headers:{
'X-Watson-Authorization-Token':decodeURI(token)
},
success:function(tone){
console.log(tone);
},
error: function(error){
console.error('Error: Couldn\'t use token: ', error);
}
});
}).fail(function(){
console.error('Error: Couldn\'t fetch watson token');
});
And the watsonToken.php file that gets the token:
<?php
$accessWatsonToken = curl_init();
$params=http_build_query(array('url' => 'https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone'));
curl_setopt($accessWatsonToken, CURLOPT_URL, "https://gateway.watsonplatform.net/authorization/api/v1/token?$params");
curl_setopt($accessWatsonToken, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($accessWatsonToken, CURLOPT_USERPWD, 'username':password');
print curl_exec($accessWatsonToken);
curl_close($accessWatsonToken);
?>