Baz Baz - 1 year ago 101
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'


//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){

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/ is returning:

What am I doing wrong?

Answer Source

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

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


    var io = require('').listen(server);


socket.on('foo', function(msg){
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download