All Posts
Dec 23, 2021

Introduction to Node Server

Building a server with Node.js is a straightforward process, perfect for beginners and professionals alike. From initializing a project to handling requests with the http module, explore the steps to create a functional, responsive server tailored to your needs.

Featured image for Introduction to Node Server

1. Start a project and create a package.json file

  • In this lesson we will primarily focus on creating a server using node js.
  • Make sure you have node installed on your computer before moving ahead.
  • Let's start by creating a folder named server on the desktop, and opening that folder on a terminal window.
  • After you open the folder on a terminal, run the following command: npm init -y.
  • By running the above command, you will notice a file named package.json is created in the folder.
  • There's nothing we will do to this file at the moment and we will get back to it later. So let's move on to step 2.

Note: By running the command npm init, we start a utility that will help us create a package.json file in our folder. Just answer a few questions or just hit enter if you are happy with the default configuration.

2. Create a server

  • Let's start by creating a file in our folder called index.js.
  • In this file we will write some code and create our first node server.
  • In order to create a server we will utilize the http module which is a core module that comes built in with the node installation.
  • We will start by importing the http module in our index.js file like this:
const http = require('http')

Note: Notice we are not importing the module using the import statement which we usually see in React. Using import is more modern way of importing modules that was introduced in ES6. When we are working with node, we use the CommonJs way of importing the modules. Commonjs is baked inside node.

  • Now we will create our server by calling a method on the http module called createServer(). The http.createServer() method creates an HTTP Server object.
  • We will save the instance of our newly created server in a variable called server.
  • Let's look at the code below:
const http = require('http')
const server = http.createServer((req, res) => {
console.log('Request has been made')
})
  • Notice in the code above, we are using the createServer() method on the http module to create a server.
  • The createServer() method will take a callback function as an argument.
  • This callback function will run every time any incoming requests come to our server.
  • This callback function (The one which is passed as an argument to createServer method) will receive request (req) and response (res) objects as parameters.
  • Our server uses the req and res objects to handle the incoming requests and outgoing responses.
  • For now, we are not doing anything in this function except logging a message in the console that says "Request has been made".

3. Make server listen to requests

  • In the step above, we created a server using the createServer method on the core http module; But notice it is not really doing anything.
  • Notice that the server is created but it's not actively listening to any incoming requests sent to it.
  • In order to make the server listen to the incoming requests, we have to invoke the listen method on our server.
  • The following piece of code will make our server listen to any incoming requests:
server.listen(5000, 'localhost', () => {
console.log('Server listening on port number 5000')
})
  • In the code above we are using the listen() method on the server instance that we created. listen() method takes a port number as its first argument. In the example code above we are passing a port number of 5000.

  • In the second argument we pass a string 'localhost'.

  • The third argument to the listen() method is a callback function that gets called when the server starts listening to the specified port number.

  • Notice, In this callback function, we are only logging some message that says "Server listening on port number 5000".

  • So far the complete code looks like this:

const http = require('http')
const server = http.createServer((req, res) => {
console.log('Request has been made')
})
server.listen(5000, 'localhost', () => {
console.log('Server listening on port number 5000')
})

Note: At this point we have a perfectly valid functional server that is ready to listen to any incoming requests on the port number 5000.

4. Start the server

  • Now we want to run the web server that we have created.
  • To do this, open up your terminal.
  • Navigate to the current working directory where we created the server, and on the terminal type the following command: node index.js.
  • Notice by running the above command on the terminal we will be presented with a message that says "Server listening on port 5000."
  • Now, let's open a web browser, and navigate to the following url: http://localhost:5000.
  • As soon as you open up this url on a web browser, you will notice another message on the terminal which says "A request is made".

Let's try to understand what just happened. In the code above we asked our server to actively listen for any incoming requests on the port number 5000. When we navigate to the url: http://localhost:5000, we are requesting for the webpage to our local web server on the port number 5000. Notice our server is listening for requests on the same port number. This incoming request from our browser will trigger the callback function that we created in the createServer method. This is why we see the second console message "A request is made."

5. Understanding the Request object

  • So far we have created a server instance that is running and listening to any incoming requests on the port number 5000.
  • We are not doing anything meaningful so far. In order to do something meaningful we have to understand the request and response objects and see what can we do with them.
  • If you log the request object in the console, you will notice its a huge object with loads of information.
  • Request object contains the url where the request is made. It also contains the method of the request (GET, POST, PUT, DELETE etc). If we send any data as a payload to the requested url, we can access this payload data in the request body.
  • Let's try to log some useful information from request object in the console.
  • Add the following piece of code in the callback function inside createServer() method:
const server = http.createServer((req, res) => {
console.log(`Request URL: ${ req.url }`)
console.log(`Request Method: ${ req.method }`)
})

Note: Every time we change or update the code, the server will not restart automatically. We have to manually stop the server from the terminal and restart the server. Press Ctrl + C to stop the server and node server.js on your terminal to restart the server.

  • After you restart the server on terminal, Open up your browser and go to the following url: http://localhost:5000/about.
  • Now on your terminal, you will notice some log messages appearing that will tell you the type of request and the request url.

6. Understanding the Response Object

  • So far you might have noticed that we are only sending some GET request to our server by visiting some urls on port 5000. Also notice that the browser must be in a continuous loading state.
  • The browser never stops loading because it is expecting some response from the server.
  • Let's start by understanding the response object and then finally send the response back to the browser.

Step 1: Response Headers

  • The first step in sending the response is to formulate and send a response header using res.setHeader() method.
  • Response headers give the browsers some extra information about what kind of response is coming back to it from the server.
  • Response headers informs the browsers on the type of data they are going to receive from the server. For example: Response headers can inform the browser that the incoming response is a Plain text, or HTML, or some JSON data coming from server. Response headers can be used to set cookies on the browsers too.
  • In order to set a response header we use the commands like this:
// Plain text response
res.setHeader('Content-Type', 'text/plain')
// HTML response
res.setHeader('Content-Type', 'text/html')
// JSON response
res.setHeader('Content-Type', 'application/json')
  • In the above commands we are setting a Content-Type header and telling the browser that the type of response is going to be either a plain text, or html, or json.

Step 2: Send a response

  • After setting the response header, the next step is to actually send a response using the res.write() method.
  • The write method takes a single argument which is the actual response we would like to send to the browser.
  • Let's take a look at some examples:
// Plain text response
res.write('Hello World')
// HTML Response
res.write('<h1>Hello World</h1>')
  • Notice in the examples above we are sending a text response and an HTML response using the write method on the response object.

Step 3: Ending the response

  • After we write the response as shown in the step above, we have to end the response.
  • This is very simple. It can be achieved using the res.end() method.

7. Sending some real response back to the browser

  • So far we learned how to create a server and the basics of request and response objects.
  • Now let's try sending some real response back to the browser and see how it looks.
  • In the following example we will send an HTML response to the browser with some heading tag and some paragraph tags.
const http = require('http')
const server = http.createServer((req, res) => {
// Using the request object to log some useful information
console.log(`Request URL: ${ req.url }`)
console.log(`Request Method: ${ req.method }`)
// Using the response object to send some html response
res.setHeader('Content-Type', 'text/html')
res.write('<h1>Home Page</h1>')
res.write('<p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>')
res.write('<p>In cupiditate, nisi repudiandae quibusdam non eveniet.</p>')
res.end()
})
server.listen(5000, 'localhost', () => {
console.log('Server listening on port number 5000')
})
  • Notice in the code above we are setting a response header informing the browser that it will receive some HTML data.
  • After that we are using the res.write() method multiple times to output an html heading tag, and 2 paragraph tags.
  • Now we can stop our running server and restart it to run the latest code we have written.
  • After restarting the server, if we visit any url on our localhost on the port 5000, we will see the HTML content we sent from our server.
  • You will also notice that the browser stopped loading now because it finally received the response from server.
  • The output will look like this on the browser: HTML response in browser

8. Sending an HTML file as a response

  • In the step above we learned how to send HTML data from server to the browser using res.write() method.
  • Notice that we are using res.write() method multiple times just to send a small block of HTML.
  • It is not a good idea to dump all the HTML inside of the res.write() method. Especially when we have a big HTML file to be sent to the browser.
  • In this step we will create an HTML file in views folder, and send this file as a response to the browser.
  • Inside the root directory of your project, create a folder called views. Inside this folder create a file called home.html. Add the following code in the newly created file and save.
<!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>Document</title>
</head>
<body>
<nav>
<a href='/'>Home</a>
<a href='/about'>About</a>
</nav>
<h1>Home Page</h1>
<p>This is the HTML coming from a file saved in the server</p>
<p>This is just a random text description...</p>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Tempore eligendi magnam minus harum nam quidem magni</p>
</body>
</html>
  • Instead of writing all the above HTML content inside the res.write() method, we will read the content from the file we just created, and we are going to send this file content as a response back to the browser.
  • In order to read the content from any file, we will make use of another core module called fs (file system) that comes built in with node js.
  • To import the fs module, we use the following command:
const fs = require('fs')
  • Now we have the fs module imported, we will try to read the content of home.html file we have created.
  • In order to read the file content, we use a method called fs.readFile(). This method will take the file path as the first argument. We also pass a callback function to readFile() method as a second argument.
  • This callback function (which is passed as a second argument to fs.readFile()) accepts 2 parameters - err and data. Let's take a look at the following example to see how we can read the content of a file.
const fs = require('fs')
fs.readFile('./views/home.html', (err, data) => {
if (err) {
console.log(err)
res.end()
} else {
res.write(data)
res.end()
}
})
  • Now after making the changes above our code looks like this:
const http = require('http')
const fs = require('fs')
const server = http.createServer((req, res) => {
// Using the request object to log some useful information
console.log(`Request URL: ${ req.url }`)
console.log(`Request Method: ${ req.method }`)
// Using the response object to send some HTML response
res.setHeader('Content-Type', 'text/html')
fs.readFile('./views/home.html', (err, data) => {
if (err) {
console.log(err)
res.end()
} else {
res.write(data)
res.end()
}
})
})
server.listen(5000, 'localhost', () => {
console.log('Server listening on port number 5000')
})
  • Now on your browser if you try to visit any url on your localhost on the port 5000, you will see the HTML content that is coming from the server after reading the file.

9. Sending different HTML files for different routes

  • At this point we know how to read content of a file and send that as a response to the browser.
  • There's one problem though. If you visit any url on your localhost on the port number 5000 you will see the exact same content.
  • So I am reading the content of an HTML file and sending it to the browser, but I am not specifying where to display this content. So If I visit http://localhost:5000, or http://localhost:5000/about, or any other url I will see the exact same content.
  • Let's fix this problem.
  • Inside of the views folder, let's create 2 more files. about.html, and 404.html.
  • What we would want to do is to display the content from about.html, when I visit http://localhost:5000/about url. If I visit http://localhost:5000 url, I would like to display the content from home.html.
  • And If I visit any other URL then I would like to display the content for 404.html
  • Add the following code in about.html and save the file.
<!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>Document</title>
</head>
<body>
<nav>
<a href='/'>Home</a>
<a href='/about'>About</a>
</nav>
<h1>About Page</h1>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Tempore eligendi magnam minus harum nam quidem magni sedest perspiciatis quod consectetur in!</p>
<p>Dolorem harum quo recusandae perspiciatis illo ipsam distinctio qui magnam et? In cupiditate, nisi repudiandae quibusdam non eveniet. Aperiam blanditiis unde adipisci ratione fuga ad tempore voluptates iusto.</p>
</body>
</html>
  • Add the following piece of code in 404.html and save the file.
<!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>Document</title>
</head>
<body>
<nav>
<a href='/'>Home</a>
<a href='/about'>About</a>
</nav>
<h1>404: Page Not Found</h1>
<p>The page you are looking for does not exist.</p>
</body>
</html>
  • Now we have 3 different HTML files created on the server. Let's understand what we would like to do on visiting the following urls:
  1. / - Show the content from home.html
  2. /about - Show the content from about.html file
  3. /any-other-url - Show the content from 404.html
  • Now inside the callback function of http.createServer() method, we have to check what is the request url. And based on the requested url, we will send different files.
  • Let's take a look at the final code:
const http = require('http')
const fs = require('fs')
const server = http.createServer((req, res) => {
// Using the request object to log some useful information
console.log(`Request URL: ${ req.url }`)
console.log(`Request Method: ${ req.method }`)
let path = './views/'
switch (req.url) {
case '/':
path += 'index.html'
break
case '/about':
path += 'about.html'
break
default:
path += '404.html'
break
}
// Using the response object to send some html response
res.setHeader('Content-Type', 'text/html')
fs.readFile(path, (err, data) => {
if (err) {
console.log(err)
res.end()
} else {
res.write(data)
res.end()
}
})
})
server.listen(5000, 'localhost', () => {
console.log('Server listening on port number 5000')
})
  • Notice in the code above we are formulating a different file path for different urls we visit from localhost. And finally we pass this dynamic file path variable as the first argument to the fs.readFile() method

10. Adding Status codes with server response

Note: Status codes are 3 digit numbers sent along with server responses. Status codes describe the type of response sent to the browser and also how successful it was.

  • Status codes describe the type of response sent to the browser and also how successful it was.
  • Let's take a look at the most common status codes:
// Most common Status codes
200 - OK
301 - Resource Permanently moved
404 - Not Found
500 - Internal Server Error
// Status Code Ranges
100 Range - Informational Responses
200 Range - Success Codes
300 Range - Redirect related Codes
400 Range - User or Client error codes
500 Range - Server error codes
  • In order to send a status code to browser, we just use use the statusCode property on the respose object and set it to some number. Example: res.statusCode = 200
  • After adding the status code with every response, our code will look like this:
const http = require('http')
const fs = require('fs')
const server = http.createServer((req, res) => {
// Using the request object to log some useful information
console.log(`Request URL: ${ req.url }`)
console.log(`Request Method: ${ req.method }`)
let path = './views/'
switch (req.url) {
case '/':
path += 'index.html'
res.statusCode = 200
break
case '/about':
path += 'about.html'
res.statusCode = 200
break
default:
path += '404.html'
res.statusCode = 404
break
}
// Using the response object to send some html response
res.setHeader('Content-Type', 'text/html')
fs.readFile(path, (err, data) => {
if (err) {
console.log(err)
res.end()
} else {
res.write(data)
res.end()
}
})
})
server.listen(5000, 'localhost', () => {
console.log('Server listening on port number 5000')
})
  • Notice in the code above we are sending a status code of 404 for sending a 404: Not Found response. For all the other responses we are setting up the status code of 200.

11. Handling Redirects

  • Let's imagine a scenario where I want to redirect a url from /about-us to just /about.
  • Since it is a permanent redirect so we have to set the statusCode to 301. res.statusCode = 301.
  • And to do the proper redirect, we have to set the response header. Let's take a look at the code below to see how it can be done.
case '/about-us':
res.statusCode = 301;
res.setHeader('Location', '/about');
res.end();
break;
  • Notice we are using the res.setHeader() method to redirect an old url to the new one.
  • After implementing this code in our index.js file, the complete code looks like this:
const http = require('http')
const fs = require('fs')
const server = http.createServer((req, res) => {
// Using the request object to log some useful information
console.log(`Request URL: ${ req.url }`)
console.log(`Request Method: ${ req.method }`)
let path = './views/'
switch (req.url) {
case '/':
path += 'index.html'
res.statusCode = 200
break
case '/about':
path += 'about.html'
res.statusCode = 200
break
case '/about-us':
res.statusCode = 301
res.setHeader('Location', '/about')
res.end()
break
default:
path += '404.html'
res.statusCode = 404
break
}
// Using the response object to send some html response
res.setHeader('Content-Type', 'text/html')
fs.readFile(path, (err, data) => {
if (err) {
console.log(err)
res.end()
} else {
res.write(data)
res.end()
}
})
})
server.listen(5000, 'localhost', () => {
console.log('Server listening on port number 5000')
})
  • At this point we can see how node works as a server, and how it can handle different requests to different routes from different web pages. And also how it can send responses back in the form of HTML pages.