VOOZH about

URL: https://www.geeksforgeeks.org/node-js/handling-requests-and-responses-in-node-js/

⇱ Handling Requests And Responses in Node.js - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Handling Requests And Responses in Node.js

Last Updated : 4 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.

Handling GET and POST Requests

Defines different behaviors for GET and POST requests.

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.

Handling Different Routes and Methods

Defines multiple routes to handle different HTTP methods.

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.
Comment

Explore