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
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 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
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.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
How to Separate Routers and Controllers in Node.js ? In a Node.js application, especially when using the Express framework, separating routers and controllers is a common practice to keep the codebase organized, maintainable, and scalable. This separation of concerns ensures that routing logic is kept separate from the business logic, making the appli
4 min read