无法在客户端收到json

时间:2016-08-29 18:54:09

标签: javascript json node.js socket.io

我的服务器如下:

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);
});

在我听的客户端使用:

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

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

但是没有任何内容输出到控制台。我可以看到以下内容在网络上不断发送:

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

http://localhost:8092/socket.io/?EIO=3&transport=polling&t=LRMGBeD正在返回:{"foo":"bar"}

我做错了什么?

1 个答案:

答案 0 :(得分:2)

emit事件foo @server,以便您可以使用on事件@client

收听

你需要在两端(服务器和客户端)使用socket.io。

服务器:

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

客户端:

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