Javascript IBM Watson WebSocket连接失败。HTTP认证失败;没有可用的有效凭据

Javascript IBM Watson WebSocket连接失败。HTTP认证失败;没有可用的有效凭据,javascript,html,reactjs,ibm-watson,Javascript,Html,Reactjs,Ibm Watson,我正在使用IBMWatson语音到文本API开发一个语音到文本web应用程序。单击按钮即可获取API。但是每当我点击按钮。我得到了上面提到的错误。我已将API密钥和URL存储在.env文件中。 我试了很多,但还是不断地犯这个错误。请帮帮我,因为我对这一切都不熟悉 我从Watson Github Repo获得了server.js Server.js 'use strict'; /* eslint-env node, es6 */ const env = require('dotenv');

我正在使用IBMWatson语音到文本API开发一个语音到文本web应用程序。单击按钮即可获取API。但是每当我点击按钮。我得到了上面提到的错误。我已将API密钥和URL存储在.env文件中。 我试了很多,但还是不断地犯这个错误。请帮帮我,因为我对这一切都不熟悉

我从Watson Github Repo获得了server.js

Server.js



'use strict';

/* eslint-env node, es6 */
const env = require('dotenv');
env.config();
const express = require('express');
const app = express();
const AuthorizationV1 = require('watson-developer-cloud/authorization/v1');
const SpeechToTextV1 = require('watson-developer-cloud/speech-to-text/v1');
const TextToSpeechV1 = require('watson-developer-cloud/text-to-speech/v1');
const vcapServices = require('vcap_services');
const cors = require('cors');

// allows environment properties to be set in a file named .env

// on bluemix, enable rate-limiting and force https
if (process.env.VCAP_SERVICES) {
  // enable rate-limiting
  const RateLimit = require('express-rate-limit');
  app.enable('trust proxy'); // required to work properly behind Bluemix's reverse proxy

  const limiter = new RateLimit({
    windowMs: 15 * 60 * 1000, // 15 minutes
    max: 100, // limit each IP to 100 requests per windowMs
    delayMs: 0 // disable delaying - full speed until the max limit is reached
  });

  //  apply to /api/*
  app.use('/api/', limiter);

  // force https - microphone access requires https in Chrome and possibly other browsers
  // (*.mybluemix.net domains all have built-in https support)
  const secure = require('express-secure-only');
  app.use(secure());
}

app.use(express.static(__dirname + '/static'));
app.use(cors())


// token endpoints
// **Warning**: these endpoints should probably be guarded with additional authentication & authorization for production use

// speech to text token endpoint
var sttAuthService = new AuthorizationV1(
  Object.assign(
    {
      iam_apikey: process.env.SPEECH_TO_TEXT_IAM_APIKEY, // if using an RC service
      url: process.env.SPEECH_TO_TEXT_URL ? process.env.SPEECH_TO_TEXT_URL  : SpeechToTextV1.URL
    },
    vcapServices.getCredentials('speech_to_text') // pulls credentials from environment in bluemix, otherwise returns {}
  )
);
app.use('/api/speech-to-text/token', function(req, res) {
  sttAuthService.getToken(function(err, token) {
    if (err) {
      console.log('Error retrieving token: ', err);
      res.status(500).send('Error retrieving token');
      return;
    }
    res.send(token);
  });
});


const port = process.env.PORT || process.env.VCAP_APP_PORT || 3002;
app.listen(port, function() {
  console.log('Example IBM Watson Speech JS SDK client app & token server live at http://localhost:%s/', port);
});

// Chrome requires https to access the user's microphone unless it's a localhost url so
// this sets up a basic server on port 3001 using an included self-signed certificate
// note: this is not suitable for production use
// however bluemix automatically adds https support at https://<myapp>.mybluemix.net
if (!process.env.VCAP_SERVICES) {
  const fs = require('fs');
  const https = require('https');
  const HTTPS_PORT = 3001;

  const options = {
    key: fs.readFileSync(__dirname + '/keys/localhost.pem'),
    cert: fs.readFileSync(__dirname + '/keys/localhost.cert')
  };
  https.createServer(options, app).listen(HTTPS_PORT, function() {
    console.log('Secure server live at https://localhost:%s/', HTTPS_PORT);
  });
}


"严格使用",;
/*eslint环境节点,es6*/
const env=require('dotenv');
env.config();
const express=require('express');
常量app=express();
const AuthorizationV1=require('watson-developer-cloud/authorization/v1');
const SpeechToTextV1=require('watson-developer-cloud/speech-to-text/v1');
const TextToSpeechV1=require('watson-developer-cloud/text-to-speechv1');
const vcapServices=require(“vcap_服务”);
const cors=需要(“cors”);
//允许在名为.env的文件中设置环境属性
//在bluemix上,启用速率限制并强制https
if(过程环境VCAP_服务){
//启用速率限制
const rate limit=require('express-rate-limit');
app.enable('trust proxy');//需要在Bluemix的反向代理后正常工作
常数限制器=新的速率限制({
windowMs:15*60*1000,//15分钟
最大值:100,//将每个IP限制为每个windowMs 100个请求
delayMs:0//禁用延迟-全速,直到达到最大限制
});
//适用于/api/*
应用程序使用(“/api/”,限制器);
//强制https-麦克风访问需要在Chrome浏览器和其他浏览器中使用https
//(*.mybluemix.net域都具有内置的https支持)
const secure=require('express-secure-only');
app.use(secure());
}
应用程序使用(express.static(u dirname+'/static');
app.use(cors())
//令牌端点
//**警告**:这些端点可能应通过额外的身份验证和授权进行保护,以供生产使用
//语音到文本令牌端点
var sttAuthService=新授权v1(
Object.assign(
{
iam_apikey:process.env.SPEECH_TO_TEXT_iam_apikey,//如果使用RC服务
url:process.env.SPEECH_TO_TEXT_url?process.env.SPEECH_TO_TEXT_url:speechtotexv1.url
},
getCredentials('speech_to_text')//从bluemix中的环境中提取凭据,否则返回{}
)
);
应用程序使用('/api/speech to text/token',函数(req,res){
getToken(函数(err,token){
如果(错误){
log('检索令牌时出错',err);
res.status(500).send('Error retrieving token');
返回;
}
res.send(令牌);
});
});
const port=process.env.port | process.env.VCAP_APP|u port | 3002;
app.listen(端口,函数(){
log('示例IBM Watson Speech JS SDK客户端应用程序和令牌服务器在http://localhost:%s/",港口),;
});
//Chrome需要https来访问用户的麦克风,除非它是本地主机url
//这将使用包含的自签名证书在端口3001上设置基本服务器
//注:这不适合生产使用
//但是,bluemix会自动在以下位置添加https支持:https://.mybluemix.net
if(!process.env.VCAP_服务){
常数fs=要求('fs');
常量https=require('https');
常量HTTPS_端口=3001;
常量选项={
key:fs.readFileSync(_dirname+'/keys/localhost.pem'),
证书:fs.readFileSync(uu dirname+'/keys/localhost.cert')
};
createServer(选项,应用程序).listen(https\u端口,函数(){
console.log('安全服务器在https://localhost:%s/,HTTPS_端口);
});
}
App.js

import React, {Component} from 'react';
import 'tachyons';
//import WatsonSpeech from 'ibm-watson';
var recognizeMic = require('watson-speech/speech-to-text/recognize-microphone');


class App extends Component {

onListenClick = () => {

  fetch('http://localhost:3002/api/speech-to-text/token')
  .then(function(response) {
      return response.text();
  }).then(function (token) {

    var stream = recognizeMic({
        token: token, // use `access_token` as the parameter name if using an RC service
        objectMode: true, // send objects instead of text
        extractResults: true, // convert {results: [{alternatives:[...]}], result_index: 0} to {alternatives: [...], index: 0}
        format: false // optional - performs basic formatting on the results such as capitals an periods
    });

    stream.on('data', function(data) {
      console.log('error 1')
      console.log(data);
    });
    stream.on('error', function(err) {
        console.log('error 2')
        console.log(err);
    });
    //document.querySelector('#stop').onclick = stream.stop.bind(stream);
  }).catch(function(error) {
      console.log('error 3')
      console.log(error);
  });
}


render() {


return(
   <div>
      <h2  className="tc"> Hello, and welcome to Watson Speech to text api</h2>
      <button onClick={this.onListenClick}>Listen to Microphone</button>
    </div>
  );
}
}

export default App


import React,{Component}来自'React';
输入‘超光速子’;
//从“ibm watson”导入WatsonSpeech;
var recognizeMic=require('watson-speech/speech-to-text/recognize麦克风');
类应用程序扩展组件{
onListenClick=()=>{
取('http://localhost:3002/api/speech-到文本/标记')
.然后(功能(响应){
返回response.text();
}).then(功能(令牌){
风险值流=可识别({
token:token,//如果使用RC服务,则使用'access\u token'作为参数名
objectMode:true,//发送对象而不是文本
extractResults:true,//将{results:[{Alternations:[…]}],结果_索引:0}转换为{Alternations:[…],索引:0}
格式:false//可选-对结果(如大写字母和句点)执行基本格式设置
});
stream.on('data',函数(data){
console.log('错误1')
控制台日志(数据);
});
stream.on('error',函数(err){
console.log('错误2')
控制台日志(err);
});
//document.querySelector('#stop').onclick=stream.stop.bind(stream);
}).catch(函数(错误){
console.log('error 3')
console.log(错误);
});
}
render(){
返回(
您好,欢迎来到沃森语音到文本api
听麦克风
);
}
}
导出默认应用程序

由于您显示的唯一代码是获取授权令牌,因此我猜这就是导致身份验证失败的原因。我不确定您使用的代码有多旧,但您使用的机制是在STT服务凭据为userid/password时使用的。当开始使用IAM密钥时,该机制变得不可靠

您的示例仍在使用watson developer cloud,但已被ibm watson取代。由于将代码迁移到IBMWatson将需要大量的返工,因此您可以继续使用watson开发者云

如果您坚持使用watson developer cloud,并且希望使用IAM密钥获得令牌,请使用:

  AuthIAMV1 = require('ibm-cloud-sdk-core/iam-token-manager/v1'),

  ...

  tokenService = new AuthIAMV1.IamTokenManagerV1({iamApikey : apikey});

  ...

  tokenService.getToken((err, res) => {
    if (err) {
      ...
    } else {
      token = res;
      ...
    }
  });


由于您显示的唯一代码是获取授权令牌,因此我猜这就是导致身份验证失败的原因。我不确定您使用的代码有多旧,但您使用的机制是在STT服务凭据为userid/password时使用的。当开始使用IAM密钥时,该机制变得不可靠

Y