Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

200
Visualizações
I can't launch my localhost websocket server

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");
});```
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You are importing your module with ESM syntax and nodejs only support CommonJs

Change

import WebSocket from 'ws';

For:

const ws = required('ws')
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda