O'Reilly logo

Node for Front-End Developers by Garann Means

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 = require("querystring"); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required