Chapter 3. Interaction with the Client
All but the simplest of sites will eventually need to send data to and receive data from the server. Itâs great that our server is delivering static filesâweâll need that for our CSS, images, and other resourcesâbut at some point weâll probably want to be able to serve a single-page application where static requests donât play as large a role. The great thing about Node is that, as JavaScript developers, we can have complete control over our API on both the client and server, and even reuse some of our code on both sides. But letâs start with setting up handling for simple GET and POST requests.
Receiving Data from the Querystring
The easiest way to pass data to the server is by adding it to the querystring. This way we donât have to do a lot of client-side setup to test our code, and if we take advantage of any of the popular client-side or server-side frameworks, weâll probably send parameters using routes, which is not so terribly different.
Node provides a querystring
module, so we donât have to
do as much parsing of the request URL to get to the querystring data. The
one thing we need to do is trim the querystring, since the
querystring
module separates out the pieces, but doesnât
separate the querystring from the rest of the URL. After adding the new
module, we can reuse the basic Hello World code we wrote, getting it to
take and process some input without needing too many changes:
var http = require("http"), querystring ...
Get Node for Front-End Developers now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.