Error on client side when using iBM Bluemix tone analyzer token fetched on server side

荒凉一梦 提交于 2019-12-12 02:46:57

问题


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);
?>

回答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>
<html lang="en">
<head>
    <title>Watson Tone Analyzer Example</title>
    <meta charset="utf-8"/>
    <script src="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>
    <div id="myoutput"></div>
</body>
</html>

<script>
analyze();

function analyze(){
  $.ajax({
       url:'/get-token.php',
          type:'GET',
          success:function(token){
              callToneAnalyzer(token);
          },
          error: function(err) {
              console.error(err);
          }
      });
}

function callToneAnalyzer(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 curl
function getToken(){
     $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();
?>


来源:https://stackoverflow.com/questions/40262937/error-on-client-side-when-using-ibm-bluemix-tone-analyzer-token-fetched-on-serve

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!