These free mini-courses will give you a strong foundation in web development. Track your progress and access advanced courses on HTML/CSS, Ruby and JavaScript for free inside our student portal.
Scroll down...
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.
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:
We're now serving HTML! Hooray! But how?
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:
Content-Type
header with a value of text/html
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);
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);
}
});
});
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!