Error On Client Side When Using Ibm Bluemix Tone Analyzer Token Fetched On Server Side
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 j
Solution 1:
I think you are trying to put X-Watson-Authorization-Token
as a body param when it should be a header and version
should be a query param. Also in your data field for your JQuery rest call you are stringifying an object that is already stringified and in the headers you are decoding the token response that does not need to be decoded
You can find out more information about how to create calls to the Watson tone analyzer service here
EDIT: Here is a full example using PHP.
index.php
<!doctype html><htmllang="en"><head><title>Watson Tone Analyzer Example</title><metacharset="utf-8"/><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script></head><body><h2>This is an example of client side call to Watson Tone analyzer service using an authorization token.</h2><divid="myoutput"></div></body></html><script>analyze();
functionanalyze(){
$.ajax({
url:'/get-token.php',
type:'GET',
success:function(token){
callToneAnalyzer(token);
},
error: function(err) {
console.error(err);
}
});
}
functioncallToneAnalyzer(token) {
$.ajax({
url:'https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone?version=2016-05-19',
type:'POST',
data: JSON.stringify({text: "this is my sample text"}),
contentType: 'application/json',
headers: {
'X-Watson-Authorization-Token': token
},
success:function(tone){
$("#myoutput").text(JSON.stringify(tone));
},
error: function(err) {
$("#myoutput").text(JSON.stringify(err));
}
});
}
</script>
get-token.php
<?php// Send a http request using curlfunctiongetToken(){
$username='YOUR-TONE-ANALYZER-USERNAME';
$password='YOUR-TONE-ANALYZER-PASSWORD';
$URL='https://gateway.watsonplatform.net/authorization/api/v1/token?url=https://gateway.watsonplatform.net/tone-analyzer/api';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $URL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_TIMEOUT, 30); //timeout after 30 seconds
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
$result=curl_exec ($ch);
curl_close ($ch);
return$result;
}
echo getToken();
?>
Post a Comment for "Error On Client Side When Using Ibm Bluemix Tone Analyzer Token Fetched On Server Side"