首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用服务器端获取的iBM蓝光音调分析器令牌时客户端出错

使用服务器端获取的iBM蓝光音调分析器令牌时客户端出错
EN

Stack Overflow用户
提问于 2016-10-26 12:57:19
回答 1查看 780关注 0票数 0

我已经在服务器端获得了一个令牌,并将其存储在cookie中,但当我使用该令牌查询api时,我似乎无法理解为什么会出现错误。

下面是我发送的jQuery ajax请求:

代码语言:javascript
复制
$.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);
        }
    });

如果我不使用dataType:jsonp,我会得到一个无访问控制源错误。当我不使用contentType:application/jsoncontentType:application/javascript时,当询问api时,我会得到一个登录对话框,询问用户名和密码。但是,既然我有了标记,我就不必传递用户名和密码了。当我以这种方式运行它时,使用dataType和contentType,我会得到一个400错误的错误请求。

有人知道我做错了什么吗?文档说我可以在客户端使用令牌,但是我必须在服务器端获取它。

更新:

根据建议,我不会通过单独的php文件的jquery调用访问服务器端代码。我能够得到令牌,但是当我将它传递给声调分析器的api调用时,我会得到一个400错误。不管我是否decodeURI令牌。

以下是我的jquery:

代码语言:javascript
复制
$.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');
});

以及获取令牌的watsonToken.php文件:

代码语言:javascript
复制
<?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);
?>
EN

回答 1

Stack Overflow用户

发布于 2016-10-26 15:55:25

我认为您正在尝试将X-Watson-Authorization-Token作为body param,而它应该是一个标头,而version应该是一个查询param。另外,在您的JQuery rest调用的数据字段中,您正在字符串化一个对象,而在标头中,您正在解码不需要解码的令牌响应。

您可以了解有关如何创建对沃森音频分析器服务这里的调用的更多信息。

编辑:下面是一个使用PHP的完整示例。

index.php

代码语言:javascript
复制
<!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

代码语言:javascript
复制
<?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();
?>
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40262937

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档