0
votes

I am trying to learn socket.io from this tutorial here. But the problem is I can't make the app run. This is the error I am getting:

XMLHttpRequest cannot load http://127.0.0.1:3000/socket.io/?EIO=3&transport=polling&t=LZFI7Tq. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 404.

This is the server side connection

var io = require('socket.io');
var socket = io.listen(3000, '127.0.0.1');

// all the people that have joined the chat
var people = {};

socket.on('connection', function (client) {
    console.log('An user connected');
    client.on('join', function(name) {
        people[client.id] = name;

        // client.emit() will only update the client that you are looking
        // at, whereas socket.sockets.emti() will update all connected clients
        client.emit('update', 'You have successfully connected..');
        socket.sockets.emit('update', name + " has joined the conversation..");
        socket.sockets.emit('update-people', people);
    });

    client.on('send', function(msg){
        socket.sockets.emit('chat', people[client.id], msg);
    });

    client.on('disconnect', function() {
        socket.sockets.emit('update', people[client.id] + ' has left the conversation..');
        delete people[client.id];
        socket.sockets.emit('update-people', people);
    });

});

And this is the client side connection

var socket = io.connect('http://127.0.0.1:3000');

I have gone through several posts related to this issue but cant solve it. Please help me.

1
You need to enable CORS. Add res.setHeader("Access-Control-Allow-Origin", "*"); in your server code. - Bidhan
Try const io = require('socket.io')(3000); at the server side (remove your second line) and var socket = io(); on the client side - mk12ok
@BidhanA, I have updated the question with all my server side code. I don't understand where do I insert that header. - Sayantan Das
@mk12ok after changing the code to what you have suggested the cors issue was gone but i got this GET http://localhost/socket.io/?EIO=3&transport=polling&t=LZFN0DQ 404 (Not Found) universalModuleDefinition:2 - Sayantan Das
You must have some sort of a server running on 127.0.0.1:3000 for this to work. The tutorial assumes that you already have a server set up(which I think you don't). Check out the "Update!" section to set up your own server. - Bidhan

1 Answers

1
votes

Add this middle-ware on the server where your cookies are created

app.use(function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept-Type');
    res.header('Access-Control-Allow-Credentials', 'true');
    next();
})