In this tutorial, our goal is to build a basic HTTP server using Node.js. We will be learning the basics of server-side programming, including how to listen and respond to HTTP requests.
What you will learn:
- Basic understanding of server-side programming
- How to create a simple HTTP server with Node.js
- How to listen and respond to HTTP requests
Prerequisites:
- Basic understanding of JavaScript
- Node.js and NPM installed on your machine
Building an HTTP server with Node.js is quite straightforward. Node.js provides a built-in module called HTTP, which allows Node.js to transfer data over the Hypertext Transfer Protocol (HTTP).
npm init -y
in your terminal.server.js
.server.js
file, add the line const http = require('http');
to import the HTTP module.http.createServer()
method to create an HTTP server.Here's an example of how to create a basic HTTP server that listens on port 3000:
// Importing the HTTP module
const http = require('http');
// Creating the server
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
// The server object listens on port 3000
server.listen(3000, '127.0.0.1', () => {
console.log("Server listening on port 3000");
});
Explanations:
- We are importing the http
module provided by Node.js
- The http.createServer()
method turns your computer into an HTTP server. It takes a callback function which will be executed each time a client makes a request to your server.
- The callback function takes two arguments: req
(the request object) and res
(the response object).
- res.statusCode
sets the status code to 200, which is HTTP for OK.
- res.setHeader()
sets the response header. Here, we are setting the content type to 'text/plain'.
- res.end()
ends the response and sends it to the client. Here, we are sending the string 'Hello World\n'.
- Finally, we tell the server to listen on port 3000.
We learned how to create a basic HTTP server using Node.js. We started by initializing a new Node.js project and then created a new JavaScript file. We imported the HTTP module and used the http.createServer()
method to create the server.
To continue learning, try adding more features to your server. You could allow it to serve HTML files, add routing, or even build a basic REST API.
Some additional resources include the Node.js docs, Mozilla Developer Network, and various online coding platforms like Codecademy.
Exercise 1: Modify the server to return a JSON response containing a greeting message.
Exercise 2: Create a server that serves a simple HTML file.
Exercise 3: Add basic routing to your server. For example, requests to '/about' could return a short bio.
Solutions:
1. To return a JSON response, you will need to change the content type to 'application/json' and the response to a JSON string.
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ message: 'Hello World' }));
fs
(filesystem) module in Node.js.const fs = require('fs');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
fs.readFile('index.html', null, function (error, data) {
if (error) {
res.writeHead(404);
res.write('Whoops! File not found!');
} else {
res.write(data);
}
res.end();
});
});
req.url
to get the URL of the request.const server = http.createServer((req, res) => {
if (req.url === '/about') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('This is the about page.');
} else {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World');
}
});
Remember to practice and experiment on your own for better understanding and mastery of the concepts.