Getting no answer Socket IO

Asked

Viewed 125 times

1

Hello,

Can you please tell me where the mistake is ?

I created a file in the root folder, server.js

var socket  = require( 'socket.io' );
var express = require('express');
var app     = express();
var server  = require('http').createServer(app);
var io      = socket.listen( server );
var port    = process.env.PORT || 3000;

server.listen(port, function () {
    console.log('Server listening at port %d', port);
});


io.on('connection', function (socket) {
	socket.on( 'new_message', function( data ) {
		io.sockets.emit( 'new_message', {			
			id: data.id,
			titulo: data.titulo,
			mensagem: data.mensagem,
			created_at: data.created_at
		});
	});
});

inserir a descrição da imagem aqui

Now in an ajax request, I include the data in the database and return in json.

My return in ajax, has the following code

if(data.success == true) {
    let socket = io.connect( 'http://'+window.location.hostname+':3000' );
    socket.emit('new_message', {
        id: data.id,
        titulo: data.titulo,
        mensagem: data.mensagem,
        created_at: data.created_at
    });
}

And I’m trying to get the answer socket as below, but I’m not succeeding.

let socket = io.connect( 'http://'+window.location.hostname+':3000' );
socket.on( 'new_message', function( data ) {
	console.log(data);
});

1 answer

0

Problem solved, the return json was like string, I added header('Content-Type: application/json'); on the return PHP and succeeded.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.