【问题标题】:No response from Directline for Azure Bot Services and blocked by CORS policyAzure 机器人服务的 Directline 没有响应并被 CORS 策略阻止
【发布时间】:2020-04-06 13:42:27
【问题描述】:

我曾使用 Microsoft Sample for Bot Services 中的 Bot Services sample

调试后,网页没有显示任何内容。 这里是我的源代码:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Web Chat: Minimal bundle with Markdown</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <script src="https://cdn.botframework.com/botframework-webchat/latest/webchat-minimal.js"></script>

    <style>
      html,
      body {
        height: 100%;
      }
      body {
        margin: 0;
      }
      #webchat {
        height: 100%;
        width: 100%;
      }
    </style>
</head>
<body>
<div id="webchat" role="main"></div>
    <script>
      (async function() {
         const res = await fetch('https://csharpbotdw.azurewebsites.net/directline/token', { method: 'POST' });
        const { token } = await res.json();
        const markdownIt = window.markdownit();
        window.WebChat.renderWebChat(
          {
                directLine: window.WebChat.createDirectLine({ token })

          },
          document.getElementById('webchat')
        );
        document.querySelector('#webchat > *').focus();
      })().catch(err => console.error(err));
    </script>
</body>
</html>

我只看到了错误提示

Access to fetch at 'https://csharpbotdw.azurewebsites.net/directline/token' from origin 'http://localhost:63191' 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. [http://localhost:63191/Test13122019]

【问题讨论】:

    标签: azure cors azure-bot-service direct-line-botframework


    【解决方案1】:

    您必须在运行 csharpbotdw 服务的应用服务的 CORS 菜单中的已批准来源列表中添加调用域。

    【讨论】:

    • 不明白。有样品吗?
    • 转到您的 csharpbotdw 服务并转到 cors 并添加您的机器人端点(客户端)
    • 我在 Azure 的 CORS 中添加了 localhost:63191,但聊天机器人未显示任何内容:显示的错误 无法加载资源:服务器响应状态为 404(未找到)[@987654322 @
    • 您需要有 fiddler 并查看请求和响应是否正常
    • 响应是错误“404Not Found”
    【解决方案2】:

    显然,您的 Azure 应用服务未在托管代码的 Azure 应用服务的 CORS 设置中正确配置 CORS。我解决了a similar issue with detailed steps here,请尝试一下它是否对您有帮助。

    您获得 directLine 令牌的 URL 似乎有问题:https://csharpbotdw.azurewebsites.net/directline/token。每次调用此 URL 时都会出现 404 错误,似乎那里没有这样的 API。

    如果您尚未在代码中实现此类 API,请在您的 .net 框架项目中尝试以下代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Text;
    using System.Threading.Tasks;
    using System.Web;
    using System.Web.Http;
    using Newtonsoft.Json;
    
    namespace CoreBot.Controllers
    {
        [Route("api/token")]
        public class TokenController : ApiController
        {
            public async Task<IHttpActionResult> token()
            {
                var secret = "<your bot channel directline secret>";
    
                HttpClient client = new HttpClient();
    
                HttpRequestMessage request = new HttpRequestMessage(
                    HttpMethod.Post,
                    $"https://directline.botframework.com/v3/directline/tokens/generate");
    
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", secret);
    
                var userId = $"dl_{Guid.NewGuid()}";
    
                request.Content = new StringContent(
                    Newtonsoft.Json.JsonConvert.SerializeObject(
                        new { User = new { Id = userId } }),
                        Encoding.UTF8,
                        "application/json");
    
                var response = await client.SendAsync(request);
                string token = String.Empty;
    
                if (response.IsSuccessStatusCode)
                {
                    var body = await response.Content.ReadAsStringAsync();
                    token = JsonConvert.DeserializeObject<DirectLineToken>(body).token;
                }
    
                var config = new ChatConfig()
                {
                    token = token,
                    userId = userId
                };
    
                return Ok(config);
            }
    
        }
    
    
        public class DirectLineToken
        {
            public string conversationId { get; set; }
            public string token { get; set; }
            public int expires_in { get; set; }
        }
        public class ChatConfig
        {
            public string token { get; set; }
            public string userId { get; set; }
        }
    }
    

    您可以在此处获取机器人频道直达密码:

    要将其集成到您的项目中,请在您的项目中的控制器文件夹下创建一个TokenController.cs 文件并将上面的代码粘贴到其中:

    在将项目发布到 Azure 后,您将能够通过 URL :https://csharpbotdw.azurewebsites.net/api/token 通过 post 方法获取令牌。

    我本地的测试结果:

    启用 CORS 并将代码发布到 Azure 后,您可以使用 HTML 代码连接到您的机器人:

        <html xmlns="http://www.w3.org/1999/xhtml">
        <head runat="server">
        <title>Web Chat: Minimal bundle with Markdown</title>
            <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        
            <script src="https://cdn.botframework.com/botframework-webchat/latest/webchat-minimal.js"></script>
        
            <style>
              html,
              body {
                height: 100%;
              }
              body {
                margin: 0;
              }
              #webchat {
                height: 100%;
                width: 100%;
              }
            </style>
        </head>
        <body>
        <div id="webchat" role="main"></div>
            <script>
              (async function() {
                 const res = await fetch('https://csharpbotdw.azurewebsites.net/api/token', { method: 'POST' });
                const { token } = await res.json();
                
                window.WebChat.renderWebChat(
                  {
                        directLine: window.WebChat.createDirectLine({ token })
        
                  },
                  document.getElementById('webchat')
                );
                document.querySelector('#webchat > *').focus();
              })().catch(err => console.error(err));
            </script>
        </body>
        </html>

    【讨论】:

    • 我试过了,还是没有反应,是不是我的HTML页面的源代码有问题?还有聊天机器人源代码?可以分享一下最后一屏源码吗?
    • 您好@EngSoonCheah,如果没有回复,您这边是否有任何异常信息?我尝试调用 url csharpbotdw.azurewebsites.net/directline/token,但出现 404 错误,请问您是否在 Chat Bot 源代码中实现了这样的 api?
    • Stanley,我没有在我的源代码中实现这样的 api。我只是按照示例 github.com/Microsoft/BotFramework-WebChat/tree/master/samples/… 进行操作,顺便说一下我应该使用哪个 URL api?
    • 嗨@EngSoonCheah,我已经更新了我的答案,如果您需要进一步的帮助,请告诉我。
    • 嗨@EngSoonCheah,你应该在你的机器人代码中自己实现那个API,如果你不知道怎么做,请告诉我你的编程语言,我会为你写一个演示。
    猜你喜欢
    • 1970-01-01
    • 2020-10-27
    • 1970-01-01
    • 2020-09-11
    • 2021-04-16
    • 2018-02-26
    • 2019-11-19
    • 2020-09-12
    • 2021-09-05
    相关资源
    最近更新 更多