I am trying to create a localhost websocket server with node 16.13 and I don't know why but I nothing seems to work. I can't launch my index.js with node index.js, I receive this error message -> 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)
Also this message in the browser 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.
In my html file I've used <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");
});```
You are importing your module with ESM syntax and nodejs only support CommonJs
Change
import WebSocket from 'ws';
For:
const ws = required('ws')