Javascript beginner, I’m trying to incorporate WebSockets into my project via socket.io, but I’m having issues getting my clientside to communicate with my server. My server is running on port 3000 and I’m running my app on port 5001 via Live Server. But, I am getting this error: Access to XMLHttpRequest at ‘http://localhost:3000/socket.io/?EIO=4&transport=polling&t=Oz_5Qur’ from origin ‘http://127.0.0.1:5001’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
The error message repeats every second or so. Any help is greatly appreciated!
index.js (server)
import express from 'express';
import { createServer } from 'node:http';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import { Server } from 'socket.io';
import cors from 'cors';
const app = express();
const server = createServer(app);
const io = new Server(server);
const __dirname = dirname(fileURLToPath(import.meta.url));
app.use(cors());
app.use('/socket.io', express.static(join(__dirname, 'node_modules', 'socket.io', 'client-dist')));
app.use(express.static(join(__dirname, 'myapp')));
console.log(__dirname);
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:5001/");
res.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE");
res.setHeader("Access-Control-Allow-Headers", "Origin, Accept, Content-Type, Authorization");
next();
})
app.get('/', (req, res) => {
res.sendFile(join(__dirname, 'server.html'));
});
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('disconnect', () => {
console.log('user disconnected');
});
});
server.listen(3000, () => {
console.log('server running at http://localhost:3000');
});
client.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<script src="https://localhost:3000/socket.io/socket.io.js"></script>
<script>
var socket = io('http://localhost:3000');
</script>
</body>
</html>
server.html(no issues)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
</script>
</body>
</html>
I’ve tried looking through many similar StackOverflow posts to no avail. I am expecting a log in the terminal that says “user connected” when a new connection is made and a log when the user disconnects.
nungchucks is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.