Baz Baz - 3 months ago 7
Javascript Question

Unable to receive json at client

My server is as follows:

var http = require('http');

//Lets define a port we want to listen to
const PORT=8092;

//We need a function which handles requests and send response
function handleRequest(request, response){

response.statusCode = 200;
response.setHeader('Content-Type', 'application/json');

response.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
response.setHeader('Access-Control-Request-Method', '*');
response.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET');
response.setHeader('Access-Control-Allow-Headers', '*');
response.setHeader('Access-Control-Allow-Credentials', 'true');

var responseBody = {
'foo': 'bar'
};

response.write(JSON.stringify(responseBody));
response.end();
}

//Create a server
var server = http.createServer(handleRequest);

//Lets start our server
server.listen(PORT, function(){
//Callback triggered when server is successfully listening. Hurray!
console.log("Server listening on: http://localhost:%s", PORT);
});


And at the client I listen using:

const socket = io('http://localhost:8092');

socket.on('foo', function(msg){
console.log(msg);
});


However nothing is outputted to the console. I can see the following being sent continuously on the network:

localhost resource-type-xhr POST HTTP 200
localhost resource-type-xhr GET HTTP 200


and http://localhost:8092/socket.io/?EIO=3&transport=polling&t=LRMGBeD is returning:
{"foo":"bar"}


What am I doing wrong?

Answer

Please emit an event foo @server so that you can listen that using on event @client

you need to use socket.io at both the ends (server and client).

server:

    var io = require('socket.io').listen(server);
    io.socket.emit('foo',{"foo":"bar"});

client:

socket.on('foo', function(msg){
   console.log(msg);
 });