javascript - 我无法启动我的本地主机 websocket 服务器
问题描述
我正在尝试使用节点 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");
});```
解决方案
您正在使用 ESM 语法导入模块,并且 nodejs 仅支持 CommonJs
改变
import WebSocket from 'ws';
为了:
const ws = required('ws')
推荐阅读
- android - 如何撤消/重做在 android 的画布上绘制的形状
- c# - 将取消令牌注入到启动中的配置方法
- reactjs - 如何从函数反应原生返回数组?
- java - jax-rs ResponseFilter 中抛出的异常不会导致回滚
- python - 使用 pyfmi 的方法 load_fmu 加载 fmu 时出错
- python-3.x - 如何检测同级子包导入以测试架构耦合规则
- python - 如何检查python数组中的重复并删除两个值
- r - 将列表放在数据框的一列中
- java - 为什么将最终字符串初始化为 args[0] 会引发 ArrayIndexOutOBoundsException?
- python - 解析 XML 以通过分组提取数据