Handling HTTP Requests with Node

A closer look at HTTP requests and how to process and respond to them with Node.

Scroll down...

Content

Resources

Comments

This lesson covers how to respond to a basic HTTP request using the native Node HTTP library. We will show you how to combine your existing knowledge of error handling on file operations with reporting back errors to the client that make the HTTP request. We'll also show you how to properly respond when all goes well server-side and return an HTML page.

Setting Up the Server

You've already seen the code that produces a "Hello world!" server with plain text. Now let's examine the code that will serve an HTML document.

var http = require('http');
var fs = require('fs');


var port = 3000;
var host = 'localhost';


var server = http.createServer(function(req, res) {
  fs.readFile('./public/index.html', 'utf8', function(err, data) {
    if (err) {
      res.writeHead(404);
      res.end("404 Not Found");
    } else {
      res.writeHead(200, {
        "Content-Type": "text/html"
      });
      res.end(data);
    }
  });
});


server.listen(port, host, function() {
  console.log(`Listening at http://${ host }:${ port }`);
});

Now let's take a quick peek at the HTML we'll be serving:

< !DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Hello Node.js Server!</title>
  </head>
  <body>
    <h1>Hello Node.js Server!</h1>
  </body>
</html>

When you visit http://localhost:3000 while this server is running you should see something like this:

Node.js hello server

We're now serving HTML! Hooray! But how?

Breaking Down Serving HTML

As you can see there is very little difference in the code above from when we output the simple "Hello world!" message in plain text. The main differences are:

  1. We're reading a file
  2. We're responding with a 404 if there is an error while reading the file
  3. We're setting a Content-Type header with a value of text/html
  4. We're sending the file data instead of a raw string

Let's address these one-by-one. First, we read the file with fs.readFile which takes the path, encoding, and callback function when file reading is complete.

  fs.readFile('./public/index.html', 'utf8', function(err, data) {
    //...
  });

Next, in the callback function, we check to see if an error has occurred by checking if err evaluates truthy. If it does then we know an error has occurred (here we assume it was the file wasn't found). In that case, we output the status code 404 for "Not Found" and output a message that the requested file was not found.

if (err) {
  res.writeHead(404);
  res.end("404 Not Found");
} else {
  //...
}

If err evaluates falsy then we know that reading the file was a success and we can respond with the file's data. In order to tell the client that the process was a success, we respond with a status code of 200 which is HTTP-speak for "OK". Next, we set a Content-Type header with a value of text/html to tell the client that the data we are sending back is HTML. This allows the browser to properly render the data as HTML.

res.writeHead(200, {
  "Content-Type": "text/html"
});
res.end(data);

Code Review

Here are the important snippets of code from this lesson.

var server = http.createServer(function(req, res) {

  // 1. Read the file
  fs.readFile('./public/index.html', 'utf8', function(err, data) {

    // 2. Check if error
    if (err) {

      // 2a. Respond with 404
      res.writeHead(404);
      res.end("404 Not Found");
    } else {

      // 3. Respond with success
      // if no error occurred!
      res.writeHead(200, {
        "Content-Type": "text/html"
      });
      res.end(data);
    }
  });
});

Wrapping Up

This lesson illustrated the basics of how to properly handle incoming HTTP requests with Node. You now should have a much clearer idea of how applications report back errors and respond with web pages when you click links and type in URLs in your address bar. We're still merely scratching the surface of what Node can do, but you already know enough to create and serve your own single page application!



Sign up to track your progress for free

There are ( ) additional resources for this lesson. Check them out!

There are no additional resources for this lesson just yet!

Sorry, comments aren't active just yet!

Next Lesson: Simple Node Server