Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

207
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda