catandmouse
catandmouse

Reputation: 11829

How to communicate with a Node.js server via a click event?

Coming from a purely front-end background, whenever a click happens to an element in the DOM, I will listen for that click and call some function to do something.

E.g. If I click on a favorite icon on a post, I can call a function to push that post into an array of favorites. But this is purely on the client side and such data isn't stored in some database (perhaps on some local storage only).

My question is, on a server environment like Node.js, how do I handle mouse events/key events and call a function in the server to do something (e.g. store something into a database)? Does that mean that upon clicking the favorite icon in my example, I need to essentially do a POST request?

Upvotes: 2

Views: 755

Answers (1)

Brad
Brad

Reputation: 163593

Does that mean that upon clicking the favorite icon in my example, I need to essentially do a POST request?

Yes, exactly. The client and server are two entirely independent applications running in independent contexts and fundamentally have nothing to do with each other on their own. To relay that data, you would have to send it over the network somehow. Your choices are HTTP, WebSockets, or WebRTC.

HTTP is a good choice for this, and you can use it with XHR or the Fetch API on the client. On the server, you'll receive these HTTP requests by setting up an HTTP server and then handling the data. Express is a package that makes this easy, but setting up routing and some other useful options.

Also, consider the new Beacon API on the client. https://developer.mozilla.org/en-US/docs/Web/API/Beacon_API This is a more efficient way of sending tracking data, and can even work after your page context is torn down. That is, you can accurately track when someone exits your page.

Upvotes: 3

Related Questions