【问题标题】:I can't launch my localhost websocket server我无法启动我的本地主机 websocket 服务器
【发布时间】:2021-12-19 17:53:23
【问题描述】:

我正在尝试使用节点 16.13 创建一个 localhost websocket 服务器,但我不知道为什么,但似乎没有任何效果。我无法使用节点 index.js 启动我的 index.js,我收到此错误消息 -> Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.(Use node --trace-warnings ... to show where the warning was created)

浏览器中也有这条消息Access to script at 'file:///.../server/index.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.

在我的 html 文件中,我使用了 <script type="module" src="./server/index.js"></script>

(index.js file) 
import WebSocket from 'ws';
    
const wss = new WebSocket.Server({ port: 8080});

const ws = new WebSocket("ws://localhost:8080");

ws.addEventListener("open", () => {
    console.log("We're connected")

    ws.send("Hey, how is going?");
});

ws.on("connection", ws => {
    console.log("New client Connected");

    ws.on("message", data => {
        console.log(`Client has sent Us: ${data}`);
    });
    
});

ws.on("close", () => {
    console.log("client has disconnected");
});```

【问题讨论】:

  • 我不知道你可以从 HTML 打开一个服务器 WebSocket,但即使你可以,它也是不对的。您需要从持久的 node.js 进程打开您的服务器 WebSocket。

标签: javascript html node.js websocket


【解决方案1】:

您正在使用 ESM 语法导入模块,并且 nodejs 仅支持 CommonJs

改变

import WebSocket from 'ws';

为:

const ws = required('ws')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-27
    • 2017-07-03
    • 2016-08-12
    • 2016-09-30
    • 2020-03-11
    • 1970-01-01
    • 2012-05-15
    • 2013-08-07
    相关资源
    最近更新 更多