V
V
Vladimir2019-10-23 15:12:02
Node.js
Vladimir, 2019-10-23 15:12:02

Why doesn't socket.emit work?

Good afternoon. Please tell me why .emit does not work, the connection works, I debugged it through the console, I get the id in the console, but I can’t transfer it to the client:
server

app.get('/tenders',auth, (req,res) => {
  
  res.sendFile(__dirname + '/tenders.html')

  io.on('connection', function(socket){

    	console.log('user connected');
    	socket.on('disconnect', () => {
    		console.log(socket.id + ' disconnected')
    	})

    	socket.emit('tender','tender');

    connection.query("SELECT * FROM tenders", function(err,res){

      const id = res.map(tenders => tenders.id);
      const category = res.map(tenders => tenders.category);
      const description = res.map(tenders => tenders.description);

      const tender = {
        id: id,
        category: category,
        description: description
      }

      console.log(tender.id[5]);

      

    })

  });
});

client
variable is always 0, and .on does nothing, so there is a problem with the server
var io = io('http://localhost:56026/tenders');

    var data = 0;

    io.on('tender', (data) => {
      data = data;
      console.log(data + ' - data');
      $('.tenders').html(data.id[0])
    });

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
h88p, 2019-10-23
@HistoryART

server

io.on('connection', socket => {
    console.log('Client connected');

    socket.on('disconnect', () => {
        console.log('Client disconnect')
    })
})


app.get('/tenders', auth, (req,res) => {
    connection.query("SELECT * FROM tenders", function(err, _res){
  
        const id = _res.map(tenders => tenders.id);
        const category = _res.map(tenders => tenders.category);
        const description = _res.map(tenders => tenders.description);
  
        const tender = {
          id: id,
          category: category,
          description: description
        }

        res.sendFile(__dirname + '/tenders.html', () => {
            io.emit('tender', tender);
        });
      })
});

client
var io = io('http://localhost:56026/tenders');
io.on('tender', (data) => {
    console.log(data + ' - data');
    $('.tenders').html(data.id[0])
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question