The beginners approach to handle requests and responses in node.js application

Follow on LinkedIn

In this article, we will understand, how we can handle requests and responses in node.js, and we will learn about the req.on() method of node.js.

Let’s see our final code and understand it step by step, to understand the node approach to handle API requests and responses.

const http = require("http");
const PORT = 5000;
const tasks = [
    { id: 1, text: 'task1' },
    { id: 2, text: 'task2' },
    { id: 3, text: 'task3' },
    { id: 4, text: 'task4' },
    { id: 5, text: 'task5' },
];

const server = http.createServer((req, res) => {
    const { method, url } = req;
    let body = [];
    req.on('data', chunk => {
        body.push(chunk);
    }).on('end', () => {
        body = Buffer.concat(body).toString();
        let status = 404;
        const response = {
            status: false,
            data: null,
            error: null
        };
        if (method === 'GET' && url === '/tasks') {
            status = 200;
            response.status = true;
            response.data = tasks;
        } else if (method === 'POST' && url === '/tasks') {
            const { id, text } = JSON.parse(body);
            if (!id || !text) {
                status = 400;
                response.error = 'Please add all the values';
            } else {
                tasks.push({ id, text });
                status = 201;
                response.status = true;
                response.data = tasks;
            }
        }
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify(response));
    });

});

server.listen(PORT);

Now, let’s understand what’s happening inside this code step by step.

const http =  require("http");

This is an HTTP module that provides the necessary functionality to create an HTTP server and handle incoming requests.

const PORT=5000;

Here setting the port number that the server will listen on.

const server = http.createServer((req, res) => {

In this line of code, we are setting a method that creates an HTTP server and takes a callback function that will be executed every time a request is received by the server.

Now, Let’s talk about our main req.on methods.

Handle requests and responses in node.js

let body=[];
req.on('data',chunk=>{
    body.push(chunk)
})

This ‘data’ event will occur whenever a chunk of data will be received, This body variable collects the data received in the request body of API.

.on('end',()=>{
    body=Buffer.concat(body).toString();

This ‘end’ event occurs when all the data has been received.

We are using Buffer in the above code because the received data is concentrated and we are converting this into the readable string.

if (method === 'GET' && url === '/tasks') {
            status = 200;
            response.status = true;
            response.data = tasks;
} else if (method === 'POST' && url === '/tasks') {
            const { id, text } = JSON.parse(body);
            if (!id || !text) {
              status = 400;
              response.error = 'Please add all the values';
} else {
            tasks.push({ id, text });
            status = 201;
            response.status = true;
            response.data = tasks;
}

These above lines of code are the conditions to check the methods and URLs, and on the basis of these methods, we are setting our response data and status.

Now, it’s time to set our headers for our API requests, and as we are sending our data in JSON format, so we need a JSON header.

res.writeHead(200,{'Content-Type':'application/json'});
res.end(JSON.stringify(response));

In the second line, we are converting our response object to a JSON string.

Server sends the response back to the client with the proper status code and the response object is converted to the JSON string.

server.listen(PORT)

This is actually starting our server, and on this port, we can access our application.

This is the basics to handle requests and responses in node.js

Thank you for reading this article, Happy Coding 🙂

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

×