Table of contents
In this blog, we will learn how to create a simple Node.js web server and handle HTTP requests.
According to Wikipedia :
A web server is computer software and the underlying hardware that accepts requests via HTTP, the network protocol created to distribute web pages or its secure variant HTTPS. A user agent, commonly a web browser or web crawler, initiates communication by making a request for a specific resource using HTTP, and the server responds with the content of that resource or an error message.
Node JS provides capabilities to create your own web server which will handle HTTP requests asynchronously.
Requirements:
Node JS (LTS)
Download from here
Basic JavaScript Understanding
Let's get started.
Create an app.js file inside your project. Inside of this JS file, we need to create our server and tell it to listen on a certain port.
We need to require an in-built library called http that is going to be used to start the server.
The http module is a core module of Node JS, so no need to install it using NPM.
So we can just create a variable called http
and require
the library.
const http = require("http");
The next thing we want to do is create a variable that tells our code what port we are going to be listening to for our server
const port = 5000;
Next, we create a
server
variable and we are going to use thathttp
library we just imported and call thecreateServer
function on this object and thiscreateServer
function takes a single function that has two parameters which is the request and the response
const server = http.createServer(function (req, res){}
Inside of the
createServer
function we are going to handle all the different activities on our server.Before writing the code inside the above function we are going to set up our server so it will listen to the port that we want it to, we have our
server
object and we will callserver.listen(port)
to tell it to listen on port 5000 and then this takes a single function that will call if there is an error.
const http = require("http"); // Import Node.js core module
const port = 5000; // port number
const server = http.createServer(function (req, res) { // creating server
//handle incoming requests here.
});
server.listen(port, function (error) {} // listen for any incoming requests
- We are going to check if an error exists and so we are going to log out a message "Something went wrong" and then we are also going to pass the error along to that log statement so that when we check our logs we can see the error but if there is no error we will log "Server is listening on port"
server.listen(port, function (error) {
if (error) {
console.log("Something went wrong", error);
} else {
console.log("Server is listening on port " + port);
}
});
Let's run our server on the terminal:
node app.js
Server is listening on port 5000
Our Server doesn't actually do anything now because we haven't implemented the function inside of the
createServer
function
The
http.createServer()
method includesrequest
andresponse
parameters which are supplied by Node JS. The request object can be used to get information about the current HTTP request e.g., URL, request header, and data. The response object can be used to send a response for a current HTTP request.Create an HTML file and by using Emmet we create a boilerplate.
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>First Server</title>
</head>
<body>
<div style="position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); color: blueviolet;">
This is my first Web Server!!
</div>
</body>
</html>
- In our
app.js
the first thing we need to do is to tell the browser that we are going to be writing HTML, to do that we will call thewriteHead
function and the first parameter ofwriteHead
is the status code of this operation and we write 200 as it is a good status code and the next parameter is going to be the different headers that you want to set and one of those headers is calledContent-type
and this will be the key of our object and then the value is going to betext/html
and this just tells the browser that the information that is being sent to it is an HTML document so it should parse it as HTML
res.writeHead(200, { "Content-Type": "text/html" });
- Next we want to read the file
index.html
so we need to import another library calledfs
about which we read about in the previous blog
const fs = require("fs");
- We are going to call the
readFile
function offs
and this function takes the name of the file that we want to read and then it is going to take a function having an error property and a data property which is going to be all the data from inside of that file and inside it, we check errors usingif-else
Finally, the Node JS web server sends the response using the end() method.
const server = http.createServer(function (req, res) {
res.writeHead(200, { "Content-Type": "text/html" });
fs.readFile("index.html", function (error, data) {
if (error) {
res.writeHead(404);
res.write("Error: File Not Found!");
} else {
res.write(data);
}
res.end();
});
});
- After restarting our server and refreshing our page we see that we are getting our HTML rendered.
We just set up our very first web server using Node JS
Source Code:
Codepen Link - codepen.io/anirudhpandaaa/pen/NWjVZjw
PS: I am currently learning node js and in sync writing these articles, if any information seems incorrect please don't hesitate to reach out!!