IBM 的文档说,以下 Node 后端代码使您能够Use the API key to have the SDK manage the lifecycle of the token. The SDK requests an access token, ensures that the access token is valid, and refreshes it if necessary.
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: '{url}',
});
如何获取令牌speechToText
以传递给在浏览器中运行的前端 Angular 应用程序?我尝试调用该方法getToken
来获取令牌:
const SpeechToTextV1 = require('ibm-watson/speech-to-text/v1');
const { IamAuthenticator } = require('ibm-watson/auth');
const speechToText = new SpeechToTextV1({
authenticator: new IamAuthenticator({
apikey: 'my-api-key',
}),
url: 'my-url',
});
speechToText.getToken(function (err, token) {
if (!token) {
console.log('error: ', err);
} else {
console.log(token);
// do more stuff with the token
}
});
那没有用。错误消息是speechToText.getToken is not a function
。我应该尝试speechToText.authenticator.getToken
吗?
我尝试从而ibm-watson/sdk
不是从获取令牌ibm-watson/speech-to-text/v1
?
const watson = require('ibm-watson/sdk');
const { IamAuthenticator } = require('ibm-watson/auth');
const authorization = new watson.AuthorizationV1({
authenticator: new IamAuthenticator({ apikey: 'my-api-key' }),
url: 'my-url'
});
authorization.getToken(function (err, token) {
if (!token) {
console.log('error: ', err);
} else {
console.log(token);
// do stuff with token
}
});
这得到了一个冒烟的新令牌。但是令牌不起作用。当我运行时,WatsonSpeech.SpeechToText.recognizeMicrophone
我收到一条错误消息HTTP Authentication failed; no valid credentials available
。
似乎每个 IBM Watson 服务都需要自己的令牌,使用特定于服务的 URL 创建。我将 Speech-to-Text URL 放入ibm-watson/sdk
,所以我应该得到正确的令牌。我不明白为什么令牌不起作用。