Handling Requests And Responses in Node.js
Last Updated :
04 Feb, 2025
Node.js is a powerful JavaScript runtime for building server-side applications. It provides an efficient way to handle HTTP requests and responses using the built-in http module or frameworks like Express.js.
Understanding HTTP Requests and Responses
An HTTP request is sent by a client (browser or API) to a server, and the server processes it to return an HTTP response. The response contains a status code, headers, and body content.
HTTP Methods
- GET: Retrieves data without modifying it, ensuring the same result for multiple requests.
- POST: Sends data to create a resource, potentially resulting in duplicates if repeated.
- PUT: Fully updates an existing resource, replacing all its current data.
- PATCH: Partially updates an existing resource, modifying only specific fields.
- DELETE: Removes a resource from the server, ensuring consistent results across requests.
HTTP Response Components
- Status Code: Represents the outcome of the request (e.g., 200 OK, 404 Not Found, 500 Server Error).
- Headers: Provide metadata about the response, such as content type and caching.
- Body: Contains the actual data sent back to the client, in formats like JSON, HTML, or plain text.
Handling Requests and Responses with HTTP Module
Node.js has a built-in http module to create an HTTP server and handle requests.
Creating a Simple HTTP Server
Creates an HTTP server that listens for requests and responds with a message.
JavaScript
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, Node.js Server!');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000');
});
Handling GET and POST Requests
Defines different behaviors for GET and POST requests.
JavaScript
const server = http.createServer((req, res) => {
if (req.method === 'GET') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Handling GET Request');
} else if (req.method === 'POST') {
let body = '';
req.on('data', chunk => { body += chunk; });
req.on('end', () => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(`Received data: ${body}`);
});
} else {
res.writeHead(405, { 'Content-Type': 'text/plain' });
res.end('Method Not Allowed');
}
});
server.listen(3000);
Handling Requests and Responses with Express.js
Express.js simplifies request and response handling with a minimal API.
Setting Up an Express Server
Initializes an Express server and sets up a basic route.
JavaScript
const express = require('express');
const app = express();
app.use(express.json());
app.get('/', (req, res) => {
res.send('Hello, Express!');
});
app.listen(3000, () => {
console.log('Express server running at http://localhost:3000');
});
Handling Different Routes and Methods
Defines multiple routes to handle different HTTP methods.
JavaScript
app.post('/data', (req, res) => {
res.json({ message: 'Data received', data: req.body });
});
app.put('/update', (req, res) => {
res.send('Resource updated successfully');
});
app.delete('/delete', (req, res) => {
res.send('Resource deleted');
});
Handling Query and URL Parameters
1. Query Parameters
Extracts query parameters from the request URL.
app.get('/search', (req, res) => {
let query = req.query.q;
res.send(`Search query: ${query}`);
});
2. URL Parameters
Retrieves dynamic values from the URL path.
app.get('/user/:id', (req, res) => {
res.send(`User ID: ${req.params.id}`);
});
Sending JSON Responses
Returns JSON-formatted responses for API requests.
app.get('/json', (req, res) => {
res.json({ framework: 'Node.js', version: '16.0.0' });
});
Handling Middleware for Requests
Middleware functions process requests before sending responses.
app.use((req, res, next) => {
console.log(`Request received: ${req.method} ${req.url}`);
next();
});
Handling Errors and Sending Custom Responses
Provides a centralized way to manage server errors.
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something went wrong!');
});
Best Practices for Handling Requests and Responses
- Use Appropriate HTTP Methods: Ensure proper method usage for clarity and security.
- Handle Errors Gracefully: Implement error handling and return meaningful responses.
- Validate Input Data: Always validate and sanitize incoming data.
Similar Reads
HTTP Request vs HapiJS Request in Node.js
Node.js: Node.js is an open-source and cross-platform runtime environment for executing JavaScript code outside a browser. You need to remember that NodeJS is not a framework and itâs not a programming language. Most of the people are confused and understand itâs a framework or a programming languag
3 min read
How to Handle a Post Request in Next.js?
NextJS is a React framework that is used to build full-stack web applications. It is used both for front-end as well as back-end. It comes with a powerful set of features to simplify the development of React applications. In this article, we will learn about How to handle a post request in NextJS. A
2 min read
Properties and Methods of Request and Response Objects in Express
Request and Response objects both are the callback function parameters and are used for Express and Node. You can get the request query, params, body, headers, and cookies. It can overwrite any value or anything there. However, overwriting headers or cookies will not affect the output back to the br
4 min read
Node.js Building simple REST API in express
Let's have a brief introduction about the Express framework before starting the code section:Express: It is an open-source NodeJs web application framework designed to develop websites, web applications, and APIs in a pretty easier way. Express helps us to handle different HTTP requests at specific
2 min read
What are Request and Cheerio in Node.js NPM ?
In this article, we are going to learn about that request and the cheerio library of node.js with their installation. Request Library: The request module is a very popular library in node.js. It helps in sending the request to the external web application to make the conversation between the client
3 min read
How to handle Child Threads in Node.js ?
Node.js is a single-threaded language and uses the multiple threads in the background for certain tasks as I/O calls but it does not expose child threads to the developer.But node.js gives us ways to work around if we really need to do some work parallelly to our main single thread process.Child Pro
2 min read
RESTful Routes in Node.js
Routing: Routing is one of the most significant parts of your website or web application. Routing in Express is basic, adaptable, and robust. Routing is the mechanism by which requests (as specified by a URL and HTTP method) are routed(directed) to the code that handles them. What is RESTful Routing
4 min read
How to make HTTP requests in Node ?
In the world of REST API, making HTTP requests is the core functionality of modern technology. Many developers learn it when they land in a new environment. Various open-source libraries including NodeJS built-in HTTP and HTTPS modules can be used to make network requests from NodeJS. There are many
4 min read
Exception Handling in Node.js
Exception handling refers to the mechanism by which the exceptions occurring in a code while an application is running is handled. Node.js supports several mechanisms for propagating and handling errors. There are different methods that can be used for exception handling in Node.js: Exception handli
3 min read
Different types of module used for performing HTTP Request and Response in Node.js
HTTP's requests and responses are the main fundamental block of the World Wide Web. There are many approaches to perform an HTTP request and Response in Node.js. Various open-source libraries are also available for performing any kind of HTTP request and Response. An HTTP request is meant to either
3 min read