Estoy tratando de crear un servidor websocket localhost con el nodo 16.13 y no sé por qué, pero parece que nada funciona. No puedo iniciar mi index.js con el nodo index.js, recibo este mensaje de error -> 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)
Además, este mensaje en el navegador 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.
En mi archivo html he usado <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"); });```Está importando su módulo con sintaxis ESM y nodejs solo admite CommonJs
Cambio
import WebSocket from 'ws';Para:
const ws = required('ws')