首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >IBM Watson WebSocket连接失败。HTTP身份验证失败;没有可用的有效凭据

IBM Watson WebSocket连接失败。HTTP身份验证失败;没有可用的有效凭据
EN

Stack Overflow用户
提问于 2019-06-05 02:30:08
回答 1查看 257关注 0票数 1

我正在开发一个使用IBM Watson Speech to text API的语音转文本web应用程序。只需单击一个按钮即可获取API。但每当我点击按钮。我得到了上面提到的错误。我已经将我的API和URL存储在一个.env文件中。我尝试了很多,但一直收到这个错误。请帮帮我,因为我对这一切都是新手。

我从Watson Github Repo那里得到了server.js

Server.js

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

App.js

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

回答 1

Stack Overflow用户

发布于 2019-06-05 17:10:29

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

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

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

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

https://stackoverflow.com/questions/56449467

复制
相关文章

相似问题

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