support@codebucket.net

How to work with Request and Response in NodeJs

How to work with Request and Response in NodeJs

K. M. Shawkat Zamil | September 19, 2022

Hello Developers,

In this tutorial, I will show you how to deal with requests and responses. First of all, we need to understand what is a request and what is the response. Request and response both are parameters of call back function. When the user wants something from the server, it is called a request. The response is the reply of the server sent to the browse.

For creating any server, we need to use the createServer() method the code is given below:

 

createServer() Method

 

const http = require('http');

const server = http.createServer((request, response) => {
  // magic happens here!
});

 

A callback function is called in the createServer() method. 

 

req.url == "/"

 

To get any URL, which means if we request anything, after the backslash, we need to write the below code:

 

var server = http.createServer(function (req, res) { 
    if (req.url == "/") {
        res.writeHead('200', { 'Content-Type': 'Text/html' })
        res.write('<h3>This is Home Page</h3>')
        res.end();
    } else if (req.url == "/about") {
        res.writeHead('200', { 'Content-Type': 'Text/html' })
        res.write('<h3>This is About Page</h3>')
        res.end();
    } else if (req.url == "/contact") {
        res.writeHead('200', { 'Content-Type': 'Text/html' })
        res.write('<h3>This is Contact Page</h3>')
        res.end();
    }

});

 

server.listen()

 

By the command server.listen(), we specify the port number. The complete code is given below:

 

var http = require('http');

var server = http.createServer(function (req, res) { 
    if (req.url == "/") {
        res.writeHead('200', { 'Content-Type': 'Text/html' })
        res.write('<h3>This is Home Page</h3>')
        res.end();
    } else if (req.url == "/about") {
        res.writeHead('200', { 'Content-Type': 'Text/html' })
        res.write('<h3>This is About Page</h3>')
        res.end();
    } else if (req.url == "/contact") {
        res.writeHead('200', { 'Content-Type': 'Text/html' })
        res.write('<h3>This is Contact Page</h3>')
        res.end();
    }

});

server.listen(5000);
console.log('Server running Successfully');

 

I hope this might help you in the journey of development.

 

Read More: How to run Hello World in Node Server

 

K. M. Shawkat Zamil

K. M. Shawkat Zamil

Senior Software Engineer

I am a Senior Software Engineer in a reputed company in Bangladesh. I am a big fan of Laravel, PHP Programming, MSSQL Server, MySql, JavaScript, and lots more. I love to help people who are especially eager to learn. I believe in patience and motivation.