【发布时间】: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();
});
【问题讨论】:
-
signalr.js长什么样子? -
Can't edit my question for some reason to add scripts.js file 基本上和docs.microsoft.com/en-us/aspnet/core/signalr/…中的一样,除了我只是想让它跨域。
-
这不是跨域问题。如果您使用的是一台服务器,那么它肯定不是跨域的。
-
请贴出源码目录结构
标签: javascript c# signalr