跨域 SignalR 导入问题

Cross-domain SignalR importing issue

甚至可以在客户端使用带有 vanilla js 的跨域 SignalR 吗? 这对我来说似乎有点不可能,因为我认为我已经尝试了一切来正确设置它。 服务器端是 .NET Core Web App,客户端只是 html、css 和 vanilla js。 如果我像这样在 scripts.js 文件中导入 SignalR:

import HubConnectionBuilder from "@microsoft/signalr"

我收到一个错误

Uncaught TypeError: Failed to resolve module specifier "@microsoft/signalr". Relative references must start with either "/", "./", or "../".

然后,我尝试将文件夹中的signalr.js文件复制过来,直接导入:

import HubConnectionBuilder from "./signalr"

我明白了

GET http://10.50.28.251:8080/FrontEnd/static/signalr net::ERR_ABORTED 404 (Not Found) 

然后如果我在它的末尾添加 .js:

import HubConnectionBuilder from "./signalr.js"

我明白了:

Uncaught SyntaxError: The requested module './signalr.js' does not provide an export named 'default'

最后我试试这个:

import * as signalR from  "./signalr.js"

var connection = new signalR.HubConnectionBuilder().withUrl("https://localhost:44368/chatHub").build();

仍然没有帮助:

Uncaught TypeError: signalR.HubConnectionBuilder is not a constructor

Scripts.js 文件:

import * as jQuery from "../../node_modules/jquery/dist/jquery.js";
jQuery
import { HubConnectionBuilder } from  "../../node_modules/@microsoft/signalr/dist/browser/signalr.js"

var connection = 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();
});

Signalr 依赖于 jquery 因此在导入之前您可以使用以下行

import $ from 'jquery';
window.jQuery = $;

未找到 js 文件,这意味着服务器不提供这些文件。如果您使用的是 wwwroot 以外的文件夹,那么您可以在 asp 核心服务器中指定它。

要自定义提供哪些静态文件,您需要修改 app.UseStaticFiles()docs 此处有更多关于如何执行此操作的详细信息。