Home > Back-end >  SocketIO send message to client via API route
SocketIO send message to client via API route

Time:12-12

I have a route in my express API where I want to emit messages using a websocket to a client. In this case, the client is another Node.js app. In this Node.js app, I try to connect to the socket and print messages received. Both the API and the Node app are on different ports. Can someone help me make this work?

Here's how I pass my socket to my express routes:

const server = app.listen(PORT, () => {
    console.log(`Server on port ${PORT}`);
});

const io = require("socket.io")(server);
app.set("socketio", io);

Here's my REST API route:

exports.getAll = function(req,res){
    var io = req.app.get('socketio');
    io.emit('hi!');
}

Here's my socket io client, it uses socket.io-client

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

socket.on("message", data => {
    console.log(data);
});

Unfortunately, I don't receive the 'hi' message from my API.

When I call /api/getAll I don't receive the message in my client app.

CodePudding user response:

When emitting an event via socket.io you have you define the event name before the data.
Example:

exports.getAll = function(req, res){
    var io = req.app.get("socketio");
    io.emit("message", "hi!");
}

Now you'll be able to receive the message event from the client.

Reference:

  • Related