From the course: Learning Node.js

Unlock the full course today

Join today to access over 23,200 courses taught by industry experts.

Create your Socket.io event

Create your Socket.io event - Node.js Tutorial

From the course: Learning Node.js

Create your Socket.io event

- [Instructor] Let's submit an event from the server to all clients notifying them of a new message. We can do this in our post message endpoint function. Let's scroll to that on line 20. And below line 21, let's add io.emit, and we'll call our event message. And we'll pass the request.body, which will contain the message. Let's save that. Then on our front end, then let's open up our index.html. And on our front end, we need to add an event listener. So let's scroll down to our script section. Then below our document ready, we'll add socket.on, and we'll check for the message event, and we'll simply call add message. And I'll rename this to add message since we're only adding a single message. And notice that I've supplied just the name of our add message function. Since its signature matches that exactly of the callback that we'd need to supply with our socket.on call. Let's give it a try after saving. So I'll refresh, and let's post a new message. It seems to work fine with one…

Contents