Javascript Can';无法在webchat中获取认知服务令牌
我正在尝试将MS botframework示例()中的Mock Bot转换为使用我自己的认知服务资源。我尝试在端点中更改区域,但没有帮助。对于下面的代码,我得到了这个错误:get net::ERR_Javascript Can';无法在webchat中获取认知服务令牌,javascript,azure,botframework,access-token,azure-cognitive-services,Javascript,Azure,Botframework,Access Token,Azure Cognitive Services,我正在尝试将MS botframework示例()中的Mock Bot转换为使用我自己的认知服务资源。我尝试在端点中更改区域,但没有帮助。对于下面的代码,我得到了这个错误:get net::ERR_ <!DOCTYPE html> <html lang="en-US"> <head> <title>Web Chat: Cognitive Services Speech Services using JavaScript</titl
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Web Chat: Cognitive Services Speech Services using JavaScript</title>
<!-- Cognitive Services Speech Services adapter is only available in full bundle -->
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!--
This CDN points to the latest official release of Web Chat. If you need to test against Web Chat's latest bits, please refer to pointing to Web Chat's MyGet feed:
https://github.com/microsoft/BotFramework-WebChat#how-to-test-with-web-chats-latest-bits
-->
<script src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"></script>
<style>
html,
body {
height: 100%;
}
body {
margin: 0;
}
#webchat {
height: 100%;
width: 100%;
}
</style>
</head>
<body>
<h1>Test</h1>
<div id="webchat" role="main"></div>
<script>
// Create a function to fetch the Cognitive Services Speech Services credentials.
// The async function created will hold expiration information about the token and will return cached token when possible.
function createFetchSpeechServicesCredentials() {
let expireAfter = 0;
let lastResult = {};
return async () => {
// Fetch a new token if the existing one is expiring.
// The following article mentioned the token is only valid for 10 minutes.
// We will invalidate the token after 5 minutes.
// https://docs.microsoft.com/en-us/azure/cognitive-services/authentication#authenticate-with-an-authentication-token
if (Date.now() > expireAfter) {
const speechServicesTokenRes = await fetch(
'https://westeurope.api.cognitive.microsoft.com/sts/v1.0/issueToken',
{ method: 'POST', headers: { 'Ocp-Apim-Subscription-Key': 'MyCognitiveServicesSubscriptionKey' } }
);
/*
const speechServicesTokenRes = await fetch(
'https://webchat-mockbot.azurewebsites.net/speechservices/token',
{ method: 'POST' }
);
*/
lastResult = await speechServicesTokenRes;//.json();
expireAfter = Date.now() + 300000;
}
return lastResult;
};
}
const fetchSpeechServicesCredentials = createFetchSpeechServicesCredentials();
async function fetchSpeechServicesRegion() {
return (await fetchSpeechServicesCredentials()).region;
}
async function fetchSpeechServicesToken() {
return (await fetchSpeechServicesCredentials()).token;
}
(async function() {
// In this demo, we are using Direct Line token from MockBot.
// Your client code must provide either a secret or a token to talk to your bot.
// Tokens are more secure. To learn about the differences between secrets and tokens.
// and to understand the risks associated with using secrets, visit https://docs.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-direct-line-3-0-authentication?view=azure-bot-service-4.0
const res = await fetch('https://directline.botframework.com/v3/directline/tokens/generate', { method: 'POST', headers: { Authorization: 'Bearer MySecret' }});
const { token } = await res.json();
// Create the ponyfill factory function, which can be called to create a concrete implementation of the ponyfill.
const webSpeechPonyfillFactory = await window.WebChat.createCognitiveServicesSpeechServicesPonyfillFactory({
// We are passing the Promise function to the authorizationToken field.
// This function will be called every time the token is being used.
authorizationToken: fetchSpeechServicesToken,
// In contrast, we are only fetching the region once.
//region: await fetchSpeechServicesRegion()
});
const store = window.WebChat.createStore({}, ({ dispatch }) => next => action => {
if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
// When we receive DIRECT_LINE/CONNECT_FULFILLED action, we will send an event activity using WEB_CHAT/SEND_EVENT
dispatch({
type: 'WEB_CHAT/SEND_EVENT',
payload: {
name: 'webchat/join',
value: { language: window.navigator.language }
}
});
}
return next(action);
});
// Pass a Web Speech ponyfill factory to renderWebChat.
// You can also use your own speech engine given it is compliant to W3C Web Speech API: https://w3c.github.io/speech-api/.
// For implementor, look at createBrowserWebSpeechPonyfill.js for details.
window.WebChat.renderWebChat(
{
directLine: window.WebChat.createDirectLine({ token }),
webSpeechPonyfillFactory,
locale: 'en-US',
store
},
document.getElementById('webchat')
);
document.querySelector('#webchat > *').focus();
})().catch(err => console.error(err));
</script>
</body>
</html>
Web聊天:使用JavaScript的认知服务语音服务
html,
身体{
身高:100%;
}
身体{
保证金:0;
}
#网络帽{
身高:100%;
宽度:100%;
}
试验
//创建一个函数以获取认知服务语音服务凭据。
//创建的异步函数将保存有关令牌的过期信息,并在可能时返回缓存的令牌。
函数createFetchSpeechServicesCredentials(){
设expireAfter=0;
设lastResult={};
返回异步()=>{
//如果现有令牌即将过期,则获取新令牌。
//下面的文章提到令牌的有效期仅为10分钟。
//我们将在5分钟后使令牌失效。
// https://docs.microsoft.com/en-us/azure/cognitive-services/authentication#authenticate-使用身份验证令牌
如果(Date.now()>expireAfter){
const speechServicesTokenRes=等待获取(
'https://westeurope.api.cognitive.microsoft.com/sts/v1.0/issueToken',
{方法:'POST',标题:{'Ocp Apim订阅密钥':'MyCognitiveServicesSubscriptionKey'}
);
/*
const speechServicesTokenRes=等待获取(
'https://webchat-mockbot.azurewebsites.net/speechservices/token',
{method:'POST'}
);
*/
lastResult=await speechServicesTokenRes;//.json();
expireAfter=Date.now()+300000;
}
返回最后的结果;
};
}
const fetchSpeechServicesCredentials=createFetchSpeechServicesCredentials();
异步函数fetchSpeechServicesRegion(){
返回(等待fetchSpeechServicesCredentials()).region;
}
异步函数fetchSpeechServicesToken(){
返回(等待fetchSpeechServicesCredentials()).token;
}
(异步函数(){
//在这个演示中,我们使用来自MockBot的直连令牌。
//您的客户端代码必须提供一个秘密或令牌才能与您的bot通信。
//令牌更安全。了解秘密和令牌之间的区别。
//要了解与使用机密相关的风险,请访问https://docs.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-direct-line-3-0-authentication?view=azure-bot-service-4.0
const res=等待取数('https://directline.botframework.com/v3/directline/tokens/generate“,{method:'POST',headers:{Authorization:'Bearer MySecret'}});
const{token}=await res.json();
//创建ponyfill工厂函数,可以调用该函数来创建ponyfill的具体实现。
const webSpeechPonyfillFactory=wait window.WebChat.createCognitiveServicesSpeechServicesPonyfillFactory({
//我们正在将承诺函数传递给authorizationToken字段。
//每次使用令牌时都会调用此函数。
授权令牌:fetchSpeechServicesToken,
//相反,我们只获取该区域一次。
//地区:等待获取SpeechServicesRegion()
});
const store=window.WebChat.createStore({},({dispatch})=>next=>action=>{
如果(action.type==='DIRECT\u LINE/CONNECT\u completed'){
//当我们收到DIRECT_LINE/CONNECT_完成的操作时,我们将使用WEB_CHAT/send_event发送事件活动
派遣({
键入:“网络聊天/发送事件”,
有效载荷:{
名称:'webchat/join',
值:{language:window.navigator.language}
}
});
}
返回下一步(操作);
});
//将Web Speech ponyfill工厂传递给renderWebChat。
//您也可以使用自己的语音引擎,因为它符合W3C Web语音API:https://w3c.github.io/speech-api/.
//对于实现者,请查看createBrowserWebSpeechPonyfill.js了解详细信息。
window.WebChat.renderWebChat(
{
directLine:window.WebChat.createDirectLine({token}),
webSpeechPonyfillFactory,
地点:“en US”,
商店
},
document.getElementById('webchat')
);
document.querySelector(“#webchat>*”).focus();
})().catch(err=>console.error(err));
请帮忙
编辑:显然,错误是SyntaxError:JSON中位置0处的意外标记e。我不确定上面产生错误的原因,但是如果我简化它,错误就会消失。试试这个对我有用的方法:
let authorizationToken;
让区域;
const speechServicesTokenRes=等待获取(
'https://westus.api.cognitive.microsoft.com/sts/v1.0/issueToken',
{方法:'POST',标题:{'Ocp Apim订阅密钥':'MyCognitiveServicesSubscriptionKey'}
);
if(speechServicesTokenRes.status==200){
地区='西欧',
authorizationToken=wait speechServicesTokenRes.text()
}否则{
返回(新错误('Error!'))
}
const webSpeechPonyfillFactory=等待窗口.WebChat.createCognitiveServicesSpeechServicesPonyfillFactory({
authorizationToken:authorizationToken,
地区:地区
} );
window.WebChat.renderWebChat({
directLine:directLine,
webSpeechPonyfillFactory:webSpeechPonyfillFactory
},document.getElementById('webchat');
希望有帮助 接受/向上投票答案服务于更大的堆栈溢出社区和任何有类似问题的人。如果你觉得我的回答足够,请“接受”