How to set up ws with express?

I have been struggling to set web socket server on my express backend. I have … Read more How to set up ws with express?

I have been struggling to set web socket server on my express backend. I have tried using following code.

const express = require('express');
const WebSocketServer = require('ws').Server;

const app = express();

const PORT = process.env.PORT || 3001;

// middlewares and routes

const server = app.listen(PORT, () => {
    console.log(`Server Started. Listening on port: ${PORT}`);
});

const webSocketServer = new WebSocketServer({ server, path: '/chat-ws' });

webSocketServer.on('connection', (ws, req) => {
    setInterval(() => ws.send(String(Date.now())), 1000);
});

trying to connect to ws using
const ws = new WebSocket('ws://localhost:3001/chat-ws')

throws the error
Refused to connect to 'ws://localhost:3001/chat-ws' because it violates the following Content Security Policy directive: "default-src 'none'". Note that 'connect-src' was not explicitly set, so 'default-src' is used as a fallback.

Source: JavaSript – Stack Overflow


Categories: NewsTags: , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *