Creating a Server in Node.js

Manvi Chaddha
Last Updated: May 13, 2022

Introduction

Node.js is a runtime environment for executing JavaScript code and is often used to build backend services. The main advantage of using Node.js is that it is super fast and highly scalable; due to this, Node.js is used in a production environment by large product-based companies, including PayPal, Uber, Netflix.  Node.js has a unique advantage because millions of front-end developers who write JavaScript for the browser can now write the server-side code and the client-side code without learning a completely different language. An application made using Java + Spring was redesigned using Node.js in PayPal. The developers found that the application made using Node.js was twice as fast with fewer people, had 33% fewer lines of code, and 40% fewer files.

This blog will teach you how to set up a server in Node.js.

Understanding HTTP Request and HTTP Response

Ever wondered what happens when you enter a URL in your browser?

The answer is whenever you enter a URL in your browser; an HTTP request is sent to the webserver; the server then responds with an HTTP response. The response has to be formatted in a specific manner adhering to the HTTP protocol for the client to make sense of it. Each HTML, CSS, and image file requires a separate HTTP request to load. That means if we have to put ten images to our webpage, that would require ten separate HTTP calls to load ten images. The below image illustrates the same.

The HTTP protocol is the foundation of any data exchange on the web and is a client-server protocol. In Node.js, there is a built-in HTTP module, which allows Node to transfer data over the HyperText Transfer Protocol. The HTTP module needs to be imported.

Check out Exporting and Importing Modules in Node.js

Creating a Basic Server in Node.js

A simple HTTP server in Node.js has become the de facto 'Hello World' for the platform. A simple web server is an excellent demonstration of the asynchronous strengths of Node.js.

Let's take a look at a very basic example of a Server in Node.js.

const http = require('http');

const requestListener = function (req, res) {
  res.writeHead(200);
  res.end('Hello, World!');
}

const server = http.createServer(requestListener);
server.listen(8080);


Let’s try to understand the program in a step by step manner

  1. Firstly we are importing the HTTP module.
  2. A function is defined called requestListener that takes in a request object and a response object as parameters.
    1. The request objects contain things such as the requested URL; note that in this particular example, we are ignoring the request parameter and returning "Hello World" always.
    2. The response object is how we send the headers and contents of the response back to the user making the request. Here we return a 200 response code (signaling a successful response) with the "Hello World" body. Other headers, such as Content-type, would also be set here.
  3. Next, the HTTP.createServer method creates a server that calls requestListener whenever a request comes in. The next line, server.listen(8080) calls the listen method, which causes the server to wait for incoming requests on the specified port - 8080, in this case.

Run the above web server by writing the node server.js command in command prompt or terminal window, and it will display a message as shown below.

Now let's see how to handle HTTP requests and send back an HTTP Response in the Node.js web server.

Handling HTTP Requests

The HTTP.createServer() method includes request and response parameters. The request object can be used to get information about the current HTTP request, URL, request header, and data. The response object can be used to send a response for a current HTTP request. The writeHead() method can provide additional information about the response, like the port number and the content type of the response.

The below program illustrates handling HTTP requests and responses in Node.js. A different response will be generated for each request corresponding to the home page, about, and contact page.

var http = require('http');

var server = http.createServer(function (req, res) {  
    if (req.url == '/') {
       
        // set response header
        res.writeHead(200, { 'Content-Type': 'text/html' });
       
        // set response content    
        res.write('<html><body><h1>This is home Page.</h1></body></html>');
        res.end();
   
    }
    else if (req.url == "/about") {
       
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.write('<html><body><h1>This is about page.</h1></body></html>');
        res.end();
   
    }
    else if (req.url == "/contact") {
       
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.write('<html><body><h1>This is contact Page.</h1></body></html>');
        res.end();
   
    }
    else
        res.end('Invalid Request!');

});

server.listen(3000);

console.log('Node.js web server at port 3000 is running..')

The req.URL is used to check the URL of the current request, and based on the request; a different response is rendered. To send a response, firstly, the response header is set using the writeHead9) method, and then a message string is set as the response body using the write() method; the Node.js web server then ends the response using the end() method.

Save the above program and run it using node filename.js as shown below:

For windows users, point your browser to http://localhost:3000 to view the following result.

You can append /contact, /about, and /anything to see the following results respectively.

By appending /contact

By appending /about

By appending anything other than /contact and /about

Sending JSON Response

In the above example, we saw how to serve HTML response corresponding to an HTTP Request. In this section, we will see how to serve a JSON Response from the Node.js web server.

var http = require('http');

var server = http.createServer(function (req, res) {  
   
    if (req.url == '/data') {
            res.writeHead(200, { 'Content-Type': 'application/json' });
            res.write(JSON.stringify({ message: "I am a JSON Response"}));  
            res.end();  
    }
});

server.listen(3000);

console.log('Node.js web server at port 3000 is running..')

The JSON.stringify() method converts a JavaScript object or value to a JSON string. Save the code above in a file called app.js and run the server using the command node app.js; the corresponding web server will be displayed in the browser, as shown below

Now we know how to set up a server in Node.js; let's look at some of the frequently asked questions related to the same.

Frequently Asked Questions

Q1) What is Node.js?

Ans 1) Node.js is a JavaScript framework for writing server-side applications. It is built on top of the Chrome v8 engine.

Q2) What is a Server?

Ans 2) A server is a computer or a system used to provide resources, data, services, or programs to other computers called clients over a network.

Key Takeaways

In this blog, we discussed setting up a server in Node.js. With this done, you may explore more related to Backend development using Node.js.

You may check out Full Stack Web Development Course — Node.js + HTML/CSS/JS on Coding Ninjas.

A common problem faced by all of us is that we prepare well, but we cannot solve the questions on time during online assessments. To overcome this, Coding Ninjas have come up with an online mock test series. The mock tests for leading companies like Amazon, Microsoft, Google, Adobe, Flipkart, TCS, Wipro, and Accenture are free. Our team of experts has curated and designed these online mock test series to help you prepare better for your coding interview rounds. In this online test series, you will get multiple tests that include the latest coding interview questions. Start preparing for the 2021 Amazon, Microsoft, etc., tech interviews now.

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think