【发布时间】:2019-11-26 15:16:17
【问题描述】:
我有一台使用 .NET Core 3 运行 SignalR 的服务器。该项目是使用模板启动的,我遵循了指南 (https://docs.microsoft.com/en-gb/aspnet/core/tutorials/signalr?tabs=visual-studio&view=aspnetcore-3.0)。
我已经创建了项目的克隆,并且可以成功连接到服务器并可以按预期接收消息。这也意味着我添加了 CORS。
我希望能够在 Node JS 环境中使用 SignalR,但连接卡在“协商”
我创建了一个全新的文件夹,运行 npm init -y 和 npm i @microsoft/signalr。
创建了一个名为 main.js 的新 js 文件,如下所示:
const signalR = require("@microsoft/signalr");
let connection = new signalR.HubConnectionBuilder()
.withUrl("http://localhost:44336/chathub")
.configureLogging(signalR.LogLevel.Trace)
.build();
connection.on("send", data => {
console.log(data);
});
connection.start()
.then(() => connection.invoke("send", "Hello"));
使用 node main.js 运行后 我在控制台中收到以下错误
[2019-11-26T14:56:14.933Z] Debug: Starting HubConnection.
[2019-11-26T14:56:14.935Z] Debug: Starting connection with transfer format 'Text'.
[2019-11-26T14:56:14.936Z] Debug: Sending negotiation request: http://localhost:44336/chathub/negotiate.
[2019-11-26T14:58:18.890Z] Warning: Error from HTTP request. Error: read ECONNRESET
[2019-11-26T14:58:18.891Z] Error: Failed to complete negotiation with the server: Error: read ECONNRESET
[2019-11-26T14:58:18.892Z] Error: Failed to start the connection: Error: read ECONNRESET
[2019-11-26T14:58:18.892Z] Debug: HubConnection failed to start successfully because of error 'Error: read ECONNRESET'.
好像超时了。服务器、客户端和 nodejs 应用程序都在本地托管。
我确保检查使用npm i 安装的信号器版本是否与服务器版本(3.0.1)匹配。我什至将 node_modules 中的 js 文件提取出来并用于另一个客户端(使用 VS 模板制作),它可以正常连接。
我不知道如何进一步调试。我尝试使用 VS 连接到服务器,但我无法获得任何信息。服务器使用 IIS Express 托管(通过 Visual Studio 启动)。 关于如何进一步调试的任何提示?否则我可能会使用另一个信号器版本降级到以前的 .NET Core 版本
我在 VS 中的 startup.cs 代码
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
//services.AddControllersWithViews();
services.AddCors(options =>
{
options.AddPolicy("AllowAll",
builder =>
{
builder
.WithOrigins("http://localhost:44399", "http://localhost:44336", "https://localhost:44399", "https://localhost:44336")
.AllowCredentials()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
services.AddSignalR();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseCors("AllowAll");
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<ChatHub>("/chathub");
});
}
}
【问题讨论】:
-
你是如何配置你的 startup.cs
-
添加了 startup.cs 类!
标签: javascript c# node.js .net-core signalr