javascript - 如何在 cordova 应用程序中使用 Watson Text2Speech REST API?

标签 javascript rest cordova ibm-cloud ibm-watson

有很多示例:How to use Watson Services in Node.JS,但是如果您使用带有 HTTP 调用的 REST API,我会遇到授权问题。

documentation API 的一部分讲述了命令行 curl 界面, 但是没有HTTP 调用 的具体示例使用 javascript 的 Web 或混合应用程序。

在我的情况下,我想在 cordova 移动应用程序中使用 Watson Text2Speech,为此我将建立一个工厂。

我使用的 http 调用确实适用于其他 API,但我在这里做错了什么? 缺少格式吗?

谁能帮忙?

看起来像这样:

.factory('GetSpeech', ['$http','$cordovaDialogs','$cordovaMedia','Base64', function($http,
                                                                                    $cordovaDialogs,
                                                                                    $cordovaMedia,
                                                                                    Base64){
  // http://ngcordova.com/docs/plugins/media/
  // https://www.ibm.com/watson/developercloud/doc/speech-to-text/input.shtml
  // https://www.npmjs.com/package/cordova-plugin-speech-recognition-feat-siri
  var watson_url = "https://stream.watsonplatform.net/text-to-speech/api/v1/synthesize";
  var watson_token_url = "https://stream.watsonplatform.net/authorization/api/v1/token?url=https://stream.watsonplatform.net/text-to-speech/api";
  var watson_token = "";
  var username='YOUR_KEY';
  var password='YOUR_PW';
  var authdata = 'Basic ' + Base64.encode(username + ':' + password);
  console.log(">>> Watson - authdata: ",authdata);
  var the_get_header = "{'Authorization':'"+ authdata +"','Content-Type':'application/json'}";

  var message = "";

  var getSpeech_innner = function (){ $http({method: 'GET',
                                            url:  watson_token_url,
                                            headers: the_get_header
                                       }).then( function successCallback(response) {
                                           console.log(">>> GetToken  Success:",response);
                                           watson_token=response;
                                           var the_post_header = "{'X-Watson-Authorization-Token':'"+ watson_token +"','Content-Type':'application/json','Accept':'audio/wav'}";
                                           var the_post_text = JSON.stringify({ "text":"This is the first sentence of the paragraph. Here is another sentence. Finally, this is the last sentence."
                                                                              });
                                           $http({
                                              method: 'POST',
                                              url: watson_url,
                                              headers: the_post_header,
                                              data: the_post_text
                                            }).then(function successCallback(response) {
                                                // this callback will be called asynchronously
                                                // when the response is available
                                                console.log(">>> GetSpeech Success:",response);
                                                message = "Success: " + response;
                                                alert(message);
                                                return true;
                                                }, function errorCallback(response) {
                                                  // called asynchronously if an error occurs
                                                  // or server returns response with an error status.
                                                  console.log(">>> GetSpeech  Error:",response);
                                                  message = "Error: " + response;
                                                  alert(message);
                                                  return false;
                                                })
                                            }, function errorCallback(response) {
                                               console.log(">>> GetToken  Error:",response);
                                            });
                                      };
  return {
    getSpeech :  getSpeech_innner
  };

}])

enter image description here

注意:顺便说一下,在 postman 中 HTTP 调用有效。 GET TokenPOST 合成

最佳答案

我用类似的方法试过:

  $http({
    method: 'POST',
    url: tts_url,
    headers: {
          'Access-Control-Allow-Origin': '*',
          'Access-Control-Allow-Headers': 'access-control-allow-headers, Authorization',
          'content-type': 'application/json',
          'Authorization': 'Basic <base64(uid:password)>',
          'Accept': 'audio/wav'
          },
    data: {'\"text\"': '\"hello world\"' },
    output: 'hello_world.wav'
    }).then(function successCallback(response) {
      console.log(">>> Success:",response.status);
    }, function errorCallback(response) {
      console.log(">>> Error:", response.status);
  });

我会得到这个错误:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://stream.watsonplatform.net/text-to-speech/api/v1/synthesize. (Reason: missing token 'access-control-allow-headers' in CORS header 'Access-Control-Allow-Headers' from CORS preflight channel).

当我删除“Access-Control-Allow-Headers” header 中的“access-control-allow-headers”条目时,行为是相同的...

在 postman 中运行相同的工作正常。

我如何允许我的 cordova 应用程序调用远程资源?

关于javascript - 如何在 cordova 应用程序中使用 Watson Text2Speech REST API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42084958/

相关文章:

重试相同请求的 HTTP 状态码

android - 如何将对我的 REST API 的访问限制为仅授权客户端?

android - 使用 RESTful Web api 将图像从 Android 应用程序上传到 azure blob 服务

javascript - 触摸屏客户端 X 和客户端 Y

javascript - 无法使用 jQuery 切换 <div>

javascript - 如何将元素 ID 变量传递给 jQuery 加载函数

javascript - 检测按键事件(移动设备)

android - 无法通过 visual studio cordova 构建签名的 android 包

android - 在 PhoneGap 中的 Android 后退按钮上停止退出 - 构建

javascript - JavaScript 中两个对象有什么区别