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.
CodePudding user response:
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.
CodePudding user response:
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.