【问题标题】:Cross-domain SignalR importing issue跨域 SignalR 导入问题
【发布时间】:2021-11-18 04:58:29
【问题描述】:

甚至可以在客户端使用带有 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();
});

【问题讨论】:

标签: javascript c# signalr


【解决方案1】:

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

要自定义提供哪些静态文件,您需要修改app.UseStaticFiles()docs 这里有更多关于如何做到这一点的细节。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 通过 npm 安装 jquery 并添加这两行代码后,现在我的 http-server 由于某种原因找不到 index.html。
    猜你喜欢
    • 2017-10-31
    • 2018-07-31
    • 2021-11-16
    • 1970-01-01
    • 2015-12-23
    • 1970-01-01
    • 1970-01-01
    • 2017-08-29
    相关资源
    最近更新 更多