Bootcamp Notes – Day 2 (Tues) – NodeJS: Week 1: Node and HTTP
Node and HTTP
Review Networking Essentials here from React Course before going on below!
Overview: Node HTTP Module
We will now look at how Node can be used to construct an HTTP server. This is where the core http module that is built into node comes to our aid. We will also be looking at a couple of other core node modules that are useful for building an http server. Recall from the earlier lesson on node modules, that we can categorize node modules in three ways and one of these ways is the node core modules built into Node.
Node Core Modules
- Built into Node, you do not need to install them
- But you do need to import them using Node’s require function when needed: eg: const http = require(‘http’);
Node HTTP Module
- http.createServer() – creates a new instance of http.Server class
- Receives a callback function as a parameter (request handler)
- When the server is listening to request, the request handler is called for every server request
- Use listen method: server.listen() — with port number and hostname to listen on
HTTP MODULE REQUEST HANDLER
- Callback with two parameters: request and response (req, res)
- req, res are objects containing information about the request from the client and the response that will be sent back to the client
- req objects contains information about the request: headers, method, url, status, and more
- res object is given information for the response: header, status, code, and more
We can set a message for the response body using write method.
- Use res.write() method to write message body, then res.end() method to complete response
- res.write(“Hello world”);
- res.end();
- The res.end method signals to the server that all of the response headers and body have been sent and that the server should consider this message complete
- Can also omit the write method and pass information for the body as an argument in the end() method
- res.end(“Hello world”);
PATH AND FILE SYSTEM MODULES
Path (path) and file system (fs) are two useful core modules of Node for when constructing a node htttp server.
- path: utilities for working with file and directory paths
- path.extname() returns file extension from given file
- path.resolve() converts relative path to absolute
- fs: utilities for interacting with local filesystem
- fs.access() checks whether a file can be accessed
- fs.createReadStream() reads from a file in small chunks of data
Node HTTP Module
- Explore the use of three core Node modules: http, fs, and path.
- Implement a simple HTTP Server that can respond to server requests.
- Serves static HTML files from a designated folder.
- Learn to use the Postman tool to test the server.
Part 1: Set up a basic server using http module
- Create a folder named node-http in the NucampFolder/5-NodeJS-Express-MongoDB folder.
- Open VS Code to this folder.
- Inside the node-http folder, create a package.json file with the following as its content:
{
"name": "node-http",
"version": "1.0.0",
"description": "Node HTTP Module Example",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server"
}
}
- Inside the node-http folder, create a file named server.js with the following as its content:
const http = require('http');
const hostname = 'localhost';
const port = 3000;
const server = http.createServer((req, res) => {
console.log(req.headers);
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.end('<html><body><h1>Hello World!</h1></body></html>');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
- Start the server by typing the following at the prompt: npm start
- Then type localhost:3000 in your browser address bar and observe the results:
- Use the Postman desktop application that you installed at the beginning of this course to send a test request to your server and observe the results.
Part 2: Serve static HTML files using path and fs modules
- Create a folder called public in the node-http folder.
- In the public folder, create a file named index.html and add the following code to it:
<html>
<head>
<title>This is index.html</title>
</head>
<body>
<h1>Index</h1>
<p>This is the content of index.html.</p>
</body>
</html>
- Similarly, create an aboutus.html file and add the following code to it:
<html>
<head>
<title>This is aboutus.html</title>
</head>
<body>
<h1>About Us</h1>
<p>This is the content of aboutus.html.</p>
</body>
</html>
- Then update server.js as follows:
const path = require('path');
const fs = require('fs');
const server = http.createServer((req, res) => {
console.log(`Request for ${req.url} by method ${req.method}`);
if (req.method === 'GET') {
let fileUrl = req.url;
if (fileUrl === '/') {
fileUrl = '/index.html';
}
const filePath = path.resolve('./public' + fileUrl);
const fileExt = path.extname(filePath);
if (fileExt === '.html') {
fs.access(filePath, err => {
if (err) {
res.statusCode = 404;
res.setHeader('Content-Type', 'text/html');
res.end(`<html><body><h1>Error 404: ${fileUrl} not found</h1></body></html>`);
return;
}
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
fs.createReadStream(filePath).pipe(res);
});
} else {
res.statusCode = 404;
res.setHeader('Content-Type', 'text/html');
res.end(`<html><body><h1>Error 404: ${fileUrl} is not an HTML file</h1></body></html>`);
}
} else {
res.statusCode = 404;
res.setHeader('Content-Type', 'text/html');
res.end(`<html><body><h1>Error 404: ${req.method} not supported</h1></body></html>`);
}
});
- Start the server, and send various requests to it and see the corresponding responses. Use both your browser and Postman to send requests. View the exercise video for details on this.
Additional Resources:
- HTTP Statuses
- MDN – An Overview of HTTP
- MDN – JSON
- MDN – XML Introduction
- Codecademy – HTTP Requests
- Network Layers
- Lifewire – The Basic Types of Network Protocols Explained
- JSON.org
- W3Schools – Node.js HTTP Module
- NodeJS – HTTP module
- Asher Shekamis – Handling HTTP requests using the ‘http’ module
- Zetcode – Node HTTP Tutorial
- NodeJS – Anatomy of an HTTP Transaction
- NodeJS – HTTP, Path, File System (fs)
- NodeJS – Class http.IncomingMessage (HTTP request)
- NodeJS – Class http.ServerResponse (HTTP response)
- NodeJS – Stream
- NodeSource – Understanding Streams in Node.js
- FlavioCopes – Node.js Streams