Open CheatSheet Back To List Next Tutorial

HTTP Module (Video Tutorial)

HTTP Module

Intro

This is the seventh in a series of tutorials on Node.js.

We created a project folder called nodejs-tutorial to hold example code from each tutorial.
The code for the whole series is available on GitHub at github.com/LearnByCheating/nodejs-tutorial

This tutorial covers the HTTP module.

Create a new directory in the nodejs-tutorial project named 7-http.
Then open your Terminal application and cd into the new folder.

Read it, watch it, do it, review it:
  • There are both a written and accompanying video version of this tutorial. There are timestamps under the headings that align with the video version of the topic.
    • Read it: For each topic heading, first read the topic. 
    • Watch it: Then watch the associated section of the video.
    • Do it: Then follow the instructions to replicate the steps on your computer.
  • The Node.js CheatSheet has a major category that aligns with this tutorial.
    • Review it: When you are done with the whole tutorial, open the CheatSheet and review the HTTP category from this tutorial. Make sure you understand everything, and can refer back to the CheatSheet when you are working on your own projects in the future. 



HTTP Overview

[0:00 Video timestamp]

HTTP stands for hypertext transfer protocol. It is the protocol for transmitting data between web browsers and web servers.


HTTP Request-Response Cycle


The HTTP Request-Response cycle:
  1. The web browser is the client. When the user types in a URL in the browser or clicks on a link, the browser sends an HTTP request over the internet, which gets routed to the website's server.
  2. The web server receives the request.
  3. The web server application processes the request by getting HTML, CSS, JavaScript and image files that are stored on the disk, and maybe pulls data from a database. If the request came with data, like if a form was filled out and submitted, it may store that data to a database. 
  4. The server returns an HTTP response to the browser. The response includes: 
    • Headers telling the browser what type of content is being sent, 
    • And the response body with the data from the page such as an HTML document, CSS styling, images, maybe some JavaScript.
  5. The client (the browser) receives the response, processes it, and displays the page.



The Node HTTP Module

[1:07 Video timestamp]

In the context of software, a Web Server is an application that handles HTTP requests. 
Node's HTTP module creates a web server.

When building a web server you will most likely use a web framework available on npm, such as Express, that uses the HTTP module. So in most cases the code examples we will be coving will be handled for you by the framework behind the scenes.


Create a very simple web server that returns plain text

[1:35 through 3:30 Video timestamps]

Create a file named server1.js and populate it with the below:

nodejs-tutorial/7-http/server1.js
const http = require('http');

const server = http.createServer((req, res) => {
  if (req.method === 'GET' && req.url === '/') {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('You are on the home page.');
  }
});

server.listen(3000);

Import the HTTP module: At the top we import the http module.

Create a server object: Then we create a server object with the http.createServer method.

Callback function:
  • It takes a callback function as the argument.
  • When an http request comes in, the callback is executed.
  • The callback has two parameters:
    1. req: One for the request object that gets created from the HTTP request, 
    2. res: And one for the response object that will send data back to the client.
  • Inside the callback we have a conditional statement that checks the request method and the URL path.
    • The request method will either be GET or POST. 
      • The GET method is a request to GET a web page from the server.
      • A POST request sends data to the server, like when the user fills out and submits a form.
    • HTTP requests are made to a URL that includes the hostname and may include a path to a specific resource on our server. 

Response:
  • In our conditional statement, if we receive a GET request to the root path of our site /, then we'll send a response.
  • The writeHead method will add a response header. It takes two arguments.
    1. The status code. 200 means the request was successful. 
    2. An object that indicates the content type. In this case we are just sending plain text.
  • In the last statement in our conditional we are adding a string of text to the response object. The end statement means we are done building the response object and to send the response now.

Listen for HTTP requests:
  • At the bottom we chain the listener method to the server object to listen for HTTP requests. 
  • Since we are in development we include a port number. We're using 3000.

Run the server:
node server1

Open the browser and go to http://localhost:3000,

That will send the HTTP request to our server and we will get our plain text response. 

To stop the server, press Control+C.



Create a server that serves HTML documents

[4:03 Video timestamp]

Let's create another server that serves HTML documents.

Create two very simple HTML documents named index.html and about.html.
They will just have a heading, and a link to the other page.

nodejs-tutorial/7-http/index.html
<!doctype html>
<html lang="en">
<body>
  <h1>Home Page</h1>
  <p>Lorem ipsum.</p>
  <a href="/about">Link to the about page</a>
</body>
</html>

nodejs-tutorial/7-http/about.html
<!doctype html>
<html lang="en">
<body>
  <h1>About</h1>
  <p>Lorem ipsum.</p>
  <a href="/">Link to the home page</a>
</body>
</html>


Create a file named server2.js and populate it with the below:
nodejs-tutorial/7-http/server2.js
const http = require('http');
const fs = require('fs');

const server = http.createServer((req, res) => {
  if (req.method === 'GET' && req.url === '/') {
    res.writeHead(200, {'Content-Type': 'text/html'})
    fs.createReadStream('./index.html', 'utf8').pipe(res);
  } else if (req.method === 'GET' && req.url === '/about') {
    res.writeHead(200, {'Content-Type': 'text/html'})
    fs.createReadStream('./about.html', 'utf8').pipe(res);
  }
});

server.listen(3000);

This server is similar to server1 except it serves HTML documents, and this time we have two routes.

Import the HTTP module: At the top we import the http module.
Import the fs module: To get the HTML documents from the disk drive we also need to import the File System module.

Create a server object: We again create a server object with the http.createServer method.

Callback function:
  • In the callback function our condition checks for two routes.
    • A GET method request to the / root URL path
    • and a GET method request to the /about URL path.

Response:
  • In the response writeHead method, the content type option is set to text/html this time, indicating we are sending an html document.
  • For GET requests to the root route / we are using the fs.createReadStream method to read the index.html file.
    • Then we pipe it as input to the response object.
  • For GET requests to the /about path we use the fs.createReadStream method to read the about.html file.
    • Then we pipe it as input to the response object.

Run the server:
Make sure you stopped the earlier server session: Control+C
Then execute server2:
node server2

Go to the browser at http://localhost:3000 and refresh the page.
You should be on the home page. 
Clicking the link will take you to the about page. 

To stop the server, press Control+C.

Open CheatSheet Back To List Next Tutorial