Node.js Tutorial: Request Handlers 🎯

beginner
5 min

Node.js Tutorial: Request Handlers 🎯

Welcome back to CodeYourCraft! Today, we're diving into one of the most fundamental concepts of Node.js - Request Handlers. By the end of this lesson, you'll be able to understand and create your own request handlers to handle incoming requests in your Node.js applications.

What are Request Handlers? 📝

In simple terms, a request handler is a function that handles incoming requests from clients (like a web browser or mobile app) and sends back responses. In Node.js, these request handlers are often referred to as route handlers or endpoints.

Why are Request Handlers Important? 💡

Request handlers are the backbone of any web application, as they allow the server to respond to client requests and carry out the necessary actions. Understanding and mastering request handlers is crucial to becoming proficient in Node.js development.

Creating a Simple Request Handler 🎯

Let's create a simple request handler to greet users.

javascript
// Import required modules const http = require('http'); // Create a simple request handler const requestHandler = (request, response) => { // Set response headers response.setHeader('Content-Type', 'text/plain'); response.setHeader('Access-Control-Allow-Origin', '*'); // Send a greeting message as the response response.end('Hello, World! 🎉\n'); }; // Create an HTTP server const server = http.createServer(requestHandler); // Start the server on a specific port server.listen(3000, () => { console.log('Server running at http://localhost:3000/'); });

In this example, we've imported the http module, created a request handler function, and used it to create an HTTP server that listens on port 3000. When a client makes a request to http://localhost:3000/, the server responds with "Hello, World!"

Request and Response Objects 📝

The request and response objects are crucial when creating request handlers. The request object contains information about the incoming request, while the response object is used to send a response back to the client.

Request Object 📝

The request object contains various properties and methods related to the incoming request, such as:

  • headers: An object containing the headers of the request
  • url: The URL of the requested resource
  • method: The HTTP method used in the request (e.g., GET, POST, PUT, DELETE)
  • query: An object containing query parameters

Response Object 📝

The response object is used to send a response back to the client. Some important methods and properties include:

  • setHeader(name, value): Sets an HTTP header for the response
  • end(data): Sends the response to the client, ending the HTTP connection
  • statusCode: The HTTP status code to be sent with the response
  • write(data): Writes data to the response body

Real-world Example 🎯

Let's create a more practical request handler example that accepts JSON data and responds with a summary of the data.

javascript
// Import required modules const http = require('http'); const url = require('url'); const querystring = require('querystring'); // Create a simple request handler const requestHandler = (request, response) => { // Parse the request body let body = ''; request.on('data', chunk => { body += chunk.toString(); }); request.on('end', () => { // Parse the JSON data const data = JSON.parse(body); // Set response headers response.setHeader('Content-Type', 'application/json'); response.setHeader('Access-Control-Allow-Origin', '*'); // Send a summary of the data as the response response.end(JSON.stringify({ name: data.name, age: data.age, occupation: data.occupation })); }); }; // Create an HTTP server const server = http.createServer(requestHandler); // Start the server on a specific port server.listen(3000, () => { console.log('Server running at http://localhost:3000/'); });

In this example, we've created a request handler that accepts JSON data, parses it, and responds with a summary of the data. When a client sends a POST request to http://localhost:3000/ with JSON data in the body, the server responds with the data summary.

Quiz 🎯

Quick Quiz
Question 1 of 1

What are request handlers in the context of Node.js?

Quick Quiz
Question 1 of 1

What are the `request` and `response` objects in the context of request handlers?