Handling Requests And Responses in Node.js
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.
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.
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.
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.
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.