V
V
Vladimir2019-11-10 02:32:42
Node.js
Vladimir, 2019-11-10 02:32:42

Why socket.io handler doesn't display data?

Good night. I had an incident, I can’t display data on sockets .. They appear for a second and disappear just as quickly .. Please help. Connection to them works.
Server:

app.get('/menu', (req,res) => {
  res.sendFile(__dirname + '/menu.html')
  connection.query('SELECT * FROM menu', (err, result) => {
    if(err) {
      console.error(err);
      return;
    }
    const index = result.reduce((acc, row) => ({...acc, [row.id]: row}), {});
    const menu = [];
    for(const row of result) {
      if(row.parent_id === 0) {
        menu.push(row);
        continue;
      }
      const parent = index[row.parent_id];
      if(!parent) {
        console.warn(`Undefined parent with id ${row.parent_id}`);
        continue;
      }
      if(!parent.children) {
        parent.children = [];
      }
      parent.children.push(row);
    }
    io.emit('menu',menu)
  });
})

Customer:
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="initial-scale=1.0,width=device-width,height=device-height,user-scalable=no">
  <title>Menu</title>
  <style type="text/css">
    nav {
      color: #555;
    }
  </style>
</head>
<body>

  <nav></nav>


  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>	

  <script type="text/javascript">

    var io = io('http://localhost:56026/');

    

      function makeMenuLevel(menuItems) {
        $(document).ready(function() {
            return `<ul>${menuItems.map(
              item =>`<li>${item.title}${item.children ? makeMenuLevel(item.children) : ''}</li>`
            ).join('')}</ul>`;
        })
      }

      io.on('menu', (data) => {
        console.log(data)
        let menu = makeMenuLevel(data)
        $('nav').append(menu)
      })

  </script>
</body>
</html>

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question