I am new to the world of web development. I am using HTTP endpoints to authenticate a user with JWT Tokens and I am also using the same tokens for authenticating the WebSocket connection as I am trying to implement real time chat functionality. I am getting ECONNREFUSED error when I am trying to test my websockets with Insomnia What could be wrong?
const express = require('express');
const http = require('http');
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const cors = require('cors');
const WebSocket = require('ws');
const authRoutes = require('./routes/AuthRoutes');
const chatRoutes = require('./routes/ChatRoutes');
const userRoutes = require('./routes/UserRoutes');
const wsManager = require('./utils/WebSocketManager');
const Authenticate = require('./middleware/Authenticate');
// Load environment variables
dotenv.config();
const MONGODB_URI = process.env.MONGODB_URI || 'MONGODB_URI=mongodb://localhost:27017/chatapp';
// Connect to MongoDB
mongoose
.connect(MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log("MongoDB connected"))
.catch((err) => console.log(err));
// Express app and middleware
const app = express();
app.use(express.json());
app.use(cors());
// Use the authentication and chat routes
app.use(authRoutes);
app.use('/chat', chatRoutes);
app.use('/users', userRoutes);
// Create HTTP server and WebSocket server
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
// WebSocket connection handling
wss.on('connection', (ws, req) => {
const token = new URLSearchParams(req.url).get('token');
// Verify the JWT token
Authenticate.verifyWebSocketToken(token)
.then((decodedToken) => {
// Add the decoded token to the WebSocket object
ws.user = decodedToken;
console.log('Client connected');
wsManager.addUser(ws);
ws.on('message', (message) => {
console.log(`Received message: ${message}`);
const parsedMessage = JSON.parse(message);
if (parsedMessage.type === 'private') {
wsManager.sendMessageToUser(ws, parsedMessage.to, parsedMessage.content);
} else {
// Handle other message types or broadcast to a room
}
});
ws.on('close', () => {
console.log('Client disconnected');
wsManager.removeUser(ws);
});
// Send an initial message to the connected client
ws.send(
JSON.stringify({
type: 'info',
message: 'WebSocket connection established.',
})
);
})
.catch((error) => {
console.log('WebSocket authentication failed:', error.message);
ws.close();
});
});
// Start the server
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));
I have tried putting websockets to different port and it did not worked I have also checked the port using lsof -i :4000 and there is one listen from node as it should be and I have correct URL on Insomnia as
ws://localhost:4000/token='tokengoeshere'