Cors Java脚本中Watson文本到语音的授权问题

Cors Java脚本中Watson文本到语音的授权问题,cors,basic-authentication,restful-authentication,ibm-watson,watson,Cors,Basic Authentication,Restful Authentication,Ibm Watson,Watson,我试图在javascript代码中使用Watson文本到语音服务。 然而,我一直在努力让它工作 如果我使用以下代码: $.ajax({ url: 'https://stream.watsonplatform.net/text-to-speech/api/v1/synthesize', type: 'POST', headers: {"Content-Type": "application/json"

我试图在javascript代码中使用Watson文本到语音服务。 然而,我一直在努力让它工作

如果我使用以下代码:

 $.ajax({
                url: 'https://stream.watsonplatform.net/text-to-speech/api/v1/synthesize',
                type: 'POST',
                headers: {"Content-Type": "application/json", "Accept": "audio/*", "Authorization": "Basic SomethingSomethingSomething=="},
                text: msgData.message[0].cInfo.text,
                output: 'output.wav',
                success: function() { 
                    console.log("text to voice complete"); 
                    var audio = new Audio('output.wav');
                    audio.play();
                }
            });
我得到:

stream.watsonplatform.net/text-to-speech/api/v1/synthesize:1 POST https://stream.watsonplatform.net/text-to-speech/api/v1/synthesize 401 (Processed)
index.html:1 Failed to load https://stream.watsonplatform.net/text-to-speech/api/v1/synthesize: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://52.207.232.200' is therefore not allowed access. The response had HTTP status code 401.
加载失败 : 不允许请求标头字段授权 访问控制允许飞行前响应中的标头

请注意,我可以很容易地从Restlet获得这样的请求

但是,如果我使用:

$.ajax({
                        url: 'https://stream.watsonplatform.net/text-to-speech/api/v1/synthesize',
                        type: 'POST',
                        user: {"something": "something"},
                        headers: {"Content-Type": "application/json", "Accept": "audio/*"},
                        data: {"text": msgData.message[0].cInfo.body},
                        output: 'output.wav',
                        success: function() {
                                console.log("text to voice complete");
                                var audio = new Audio('output.wav');
                                audio.play();
                        }
                });
我得到:

stream.watsonplatform.net/text-to-speech/api/v1/synthesize:1 POST https://stream.watsonplatform.net/text-to-speech/api/v1/synthesize 401 (Processed)
index.html:1 Failed to load https://stream.watsonplatform.net/text-to-speech/api/v1/synthesize: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://52.207.232.200' is therefore not allowed access. The response had HTTP status code 401.

看起来IBM Watson Text-To-Speech确实支持部分CORS(在您的情况下需要)。请核对答案:

此外,您还会发现一条明智的建议,告诉您不要在JavaScript代码中添加Watson凭据,而要使用令牌:

当您在客户端工作时,也许试用Watson的NPM模块或库(带有示例)将是一个不错的选择:

希望这有帮助