【发布时间】:2020-03-31 14:03:32
【问题描述】:
我有一个 azure 聊天机器人,我在每个直线频道都使用它。 如果我直接在 HTML 中使用秘密,它工作正常,但出于安全原因,我想使用令牌。这就是我使用它的原因:
<script>
window
.fetch('http://XXXXXXXX.azurewebsites.net/token-generate',
{
method: 'POST'
})
.then(function(res) {
return res.json();
})
.then(function(json) {
const token = json.token;
window.WebChat.renderWebChat({
directLine: window.WebChat.createDirectLine({
token: token
})
},
document.getElementById('webchat'));
document.querySelector('#webchat > *').focus();
});
</script>
就是这样,而不是异步函数,因为它也需要在 IE11 上工作。
我的机器人中的 index.js 如下所示:
// Create HTTP server
const server = restify.createServer({
name: 'token-server'
});
server.listen(process.env.port || process.env.PORT || 3978, function() {
console.log(`\n${ server.name } listening to ${ server.url }`);
console.log('\nGet Bot Framework Emulator: https://aka.ms/botframework-emulator');
console.log('\nTo talk to your bot, open the emulator select "Open Bot"');
});
server.post('/token-generate', async (_, res) => {
console.log('requesting token ');
res.setHeader('Access-Control-Allow-Origin', '*');
console.log(res);
try {
const cres = await fetch('https://directline.botframework.com/v3/directline/tokens/generate', {
headers: {
authorization: `Bearer ${ process.env.DIRECT_LINE_SECRET }`
},
method: 'POST'
});
// console.log(cres);
const json = await cres.json();
// console.log(json);
// json.header.append('Access-Control-Allow-Origin: *');
console.log(json);
if ('error' in json) {
res.send(500);
} else {
res.send(json);
}
} catch (err) {
res.send(500);
}
});
这是我在研究如何使用令牌呈现网络聊天后发现的一些代码。
我的问题是,当我使用这个 html 代码时,我得到了一些错误:
Access to fetch at 'http://compliancebotbbraun-bot.azurewebsites.net/token-generate' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
testbot.html:1 Uncaught (in promise) TypeError: Failed to fetch
我只是不知道如何更改 Access-Control-Allow-Origin 标头。我在网上找不到任何东西,如果我找到东西,它甚至与我的代码都不接近。 它的工作方式与我认为它在 IE11 中的工作方式完全相同,但在 Chrome、Edge 和 Firefox(其他人的 idk,仅测试过这些)中,这些错误正在发生。
我希望这里有人可以帮助我。
【问题讨论】:
-
你在bot的应用设置中设置了CORS设置吗?
-
在哪里更改我的机器人的 CORS 设置?当我搜索它时没有找到任何东西,并且我需要更改我的一些代码。
-
Stanley Gong 为您提供了一个很好的分步指南。
标签: javascript node.js azure token chatbot