如何使用socket.io使用Node.js Rest API?

时间:2018-12-27 06:25:15

标签: node.js socket.io

io.on('connection', function (socket)
{
    console.log('a client connected');
    app.get('/names', function (req, res)
    {
        con.query('SELECT * FROM demo', (err, rows) =>
        {
            if(err) throw err;
            res.send(rows);
            console.log(rows);
            console.log('Data received from Db:\n');
            console.log(rows);
            res.json({
                message:'retrieved successfully'
            })
            //socket.emit('showrows', rows);
        })
    });
}

在连接到服务器时api命中正常,

1 个答案:

答案 0 :(得分:1)

分别设置快递路线。不要将它们添加到socket.io回调中。

const express = require("express");
const app = express();
const server = require("http").createServer(app);
const io = require("socket.io")(server);
const PORT = process.env.PORT || 3000;

io.on("connection", socket => {
  console.log("onConnection");

  socket.on("disconnect", () => {
    console.log("onDisconnect");
  });
});

app.get('/names', (req, res) => {
  con.query('SELECT * FROM demo', (err, rows) => {
    if (err) 
      throw err;
    res.send(rows);
    console.log(rows);
    console.log('Data received from Db:\n');
    console.log(rows);
    res.json({message: 'retrieved successfully'})
    //socket.emit('showrows', rows);
  })
});

server.listen(PORT, err => {
  if (err) 
    process.nextTick(err);

  console.log(`Service running at ${PORT}`);
});