IBM IAM IamAuthenticator getToken 不是函数

IBM IAM IamAuthenticator getToken is not a function

我正在尝试获取令牌以在我的应用程序中使用 IBM Watson Speech-to-Text。这是我的代码:

const { IamAuthenticator } = require('ibm-cloud-sdk-core');

const authenticator = new IamAuthenticator({
    apikey: 'myApiKey',
  });

  authenticator.getToken(function (err, token) {
    if (!token) {
      console.log('error: ', err);
    } else {
      // use token
    }
  });

错误信息是authenticator.getToken is not a function

documentation 说:

string IBM.Cloud.SDK.Core.Authentication.Iam.IamAuthenticator.GetToken  (       )   

getTokenGetToken 我都试过了。同样的错误信息。代码并不复杂,我做错了什么?

这是对我有用的最新 ibm-watson node-sdk,

使用此命令安装 node-sdk

npm install --save ibm-watson

然后,在您的 app.jsserver.js 节点文件中使用此代码段来接收 IAM 访问令牌

const watson = require('ibm-watson/sdk');
const { IamAuthenticator } = require('ibm-watson/auth');

// to get an IAM Access Token
const authorization = new watson.AuthorizationV1({
  authenticator: new IamAuthenticator({ apikey: '<apikey>' }),
  url: ''
});

authorization.getToken(function (err, token) {
  if (!token) {
    console.log('error: ', err);
  } else {
    console.log('token: ', token);
  }
});

您也可以直接将 IamAuthenticator 与 Speech to Text 一起使用

const fs = require('fs');
const SpeechToTextV1 = require('ibm-watson/speech-to-text/v1');
const { IamAuthenticator } = require('ibm-watson/auth');

const speechToText = new SpeechToTextV1({
  authenticator: new IamAuthenticator({ apikey: '<apikey>' }),
  url: 'https://stream.watsonplatform.net/speech-to-text/api/'
});

const params = {
  // From file
  audio: fs.createReadStream('./resources/speech.wav'),
  contentType: 'audio/l16; rate=44100'
};

speechToText.recognize(params)
  .then(response => {
    console.log(JSON.stringify(response.result, null, 2));
  })
  .catch(err => {
    console.log(err);
  });

// or streaming
fs.createReadStream('./resources/speech.wav')
  .pipe(speechToText.recognizeUsingWebSocket({ contentType: 'audio/l16; rate=44100' }))
  .pipe(fs.createWriteStream('./transcription.txt'));

在您的 中查看我的回答可能会有帮助。如果您想自己管理令牌身份验证过程,请使用 BearerTokenAuthenticator