Chapter 8: Connect

Node.js provides basic APIs for common network applications. So far, you have looked at the basic APIs for TCP servers and an API for HTTP that builds on top of it.

Most real-world applications, however, perform a series of common tasks that you probably don’t want to re-implement on top of primitive APIs over and over again.

Connect is a toolkit that sits on top of the HTTP server to provide a new way of organizing code that interfaces with request and responses, around units called middleware.

To illustrate the benefits of code reuse through middleware, assume this sample structure for a website:

$ ls website/

index.html  images/

Under the images directory, you have four images:

$ ls website/images/

1.jpg  2.jpg  3.jpg  4.jpg

The index.html simply displays the four images, and you want to access the website through http://localhost as in other examples (see Figure 8-1):

<h1>My website</h1>

<img src=”/images/1.jpg”>

<img src=”/images/2.jpg”>

<img src=”/images/3.jpg”>

<img src=“/images/4.jpg“>

9781119963103-fg0801.eps

Figure 8-1: A simple static website demonstrating Connect’s capabilities

To show the simplicity Connect offers for the world of HTTP applications, this chapter shows how to write this simple website with the native http API and later with the connect API.

A simple website with HTTP

As usual, you start by requiring the http module for the server and ...

Get Smashing Node.js: JavaScript Everywhere, 2nd Edition 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.