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

211
Visualizações
Websocket connection fails on localhost because of Content Security Policy?

So, I'm using ws package for my backend, and this is my server that I copied from getting started page:

import { WebSocketServer } from 'ws'

const wss = new WebSocketServer({ port: 8080 })

wss.on('connection', function connection(ws) {
  ws.on('message', function message(data) {
    console.log('received: %s', data)
  })

  ws.send('something')
})

Now, in my browser console I run this :

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

I get an error:

Content Security Policy: The page’s settings blocked the loading of a resource at ws://localhost:8080/ (“connect-src”).

I've done some googling, and it seems like the connection should be secure in order it to work? However, MDN and other sources do not mention it anywhere. Am I doing something wrong? I'd appreciate any help.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

This error is due to Content Security Policy (mdn) as it's written over there. And if you were running a local server and tried this in that, it would've been worked.

in my browser console I run this

So, here is a problem. The new tab, or wherever you've run this, might have blocked this request to protect against XSS or something like that. The easiest thing to make this work is to add a meta tag <meta http-equiv="Content-Security-Policy" content="connect-src 'ws://localhost:8080';"> to the HTML page or run a local server.

about 4 years ago · Juan Pablo Isaza Relatório

0

Creating a websocket connection in a browser console was failing for some reason, however, after I created a simple html page with a script it worked without any problems:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body></body>
  <script>
    const socket = new WebSocket('ws://localhost:8080')
    console.log(socket)
  </script>
</html>

I hope it saves some time for other people.

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