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
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
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
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
API Response Caching using apicache Middleware in Node.js
APIs are a crucial part of modern web applications, providing the means for different software systems to communicate and exchange data. However, frequent API calls, especially to the same endpoints, can lead to increased server load, slower response times, and higher bandwidth usage. Caching is a s
4 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
Node.js http.ServerResponse.headersSent Property
The httpServerResponse.headersSent is an inbuilt application programming interface of class ServerResponse within the HTTP module which is used to check if the header has been sent or not. Syntax: const response.headersSentParameters: This property does not accept any arguments as a parameter. Retur
2 min read
How to Detect AJAX Request to Normal Request in Node.js ?
When developing web applications with Node.js, you often need to differentiate between AJAX (Asynchronous JavaScript and XML) requests and normal HTTP requests. AJAX requests are typically used to fetch data without reloading the entire page, while normal requests often result in full page loads. De
3 min read
Node.js http.ServerResponse.end() Method
The httpServerResponse.end() is an inbuilt application programming interface of class Server Response within http module which is used to send the signal to the server that all the header has been sent. Syntax: response.end(data, Encodingtype, Callbackfunction) Parameters: This method takes three Pa
2 min read
Node.js http.ServerResponse.socket Api
The httpServerResponse.socket is an inbuilt application programming interface of class ServerResponse within http module which is used to get the reference of the underlying socket object. Syntax: response.socket Parameters: This method does not accept any arguments as a parameter. Return Value: Thi
2 min read