【发布时间】:2021-11-16 09:39:36
【问题描述】:
尝试制作 Microsoft SignalR 入门的跨域版本: https://docs.microsoft.com/en-us/aspnet/core/tutorials/signalr?view=aspnetcore-5.0&tabs=visual-studio 我遇到了很多问题。我已经在服务器端配置了 CORS。 但是控制台向我显示了这个:
GET http://10.50.2.87:8080/node_modules/signalr/dist/browser/signalr net::ERR_ABORTED 404 (Not Found)
不确定为什么它不起作用。 scripts.js 文件:
import * as signalR from "./node_modules/signalr/dist/browser/signalr"
var connection = new signalR.HubConnectionBuilder().withUrl("https://localhost:44368/chatHub").build();
//Disable send button until connection is established
document.getElementById("sendButton").disabled = true;
connection.on("ReceiveMessage", function (user, message) {
var li = document.createElement("li");
document.getElementById("messagesList").appendChild(li);
// We can assign user-supplied strings to an element's textContent because it
// is not interpreted as markup. If you're assigning in any other way, you
// should be aware of possible script injection concerns.
li.textContent = `${user} says ${message}`;
});
connection.start().then(function () {
document.getElementById("sendButton").disabled = false;
}).catch(function (err) {
return console.error(err.toString());
});
document.getElementById("sendButton").addEventListener("click", function (event) {
var user = document.getElementById("userInput").value;
var message = document.getElementById("messageInput").value;
connection.invoke("SendMessage", user, message).catch(function (err) {
return console.error(err.toString());
});
event.preventDefault();
});
ChatHub 类:
using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;
namespace SignalRChat.Hubs
{
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
}
这样配置 CORS:
services.AddCors(options =>
{
options.AddDefaultPolicy(builder => builder.WithOrigins("http://10.50.2.87:8080/")
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod());
});
我在 html 文件的末尾添加了这两行:
<script src="/node_modules/@microsoft/signalr/dist/browser/signalr.js"></script>
<script type="module" src="./scripts.js"></script>
页面上的按钮处于活动状态,这意味着前端正在连接到服务器端的集线器,但是当我点击它时没有任何反应。
【问题讨论】:
标签: javascript c# signalr