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.
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.
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.
Let's create a simple request handler to greet users.
// 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!"
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.
The request object contains various properties and methods related to the incoming request, such as:
headers: An object containing the headers of the requesturl: The URL of the requested resourcemethod: The HTTP method used in the request (e.g., GET, POST, PUT, DELETE)query: An object containing query parametersThe 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 responseend(data): Sends the response to the client, ending the HTTP connectionstatusCode: The HTTP status code to be sent with the responsewrite(data): Writes data to the response bodyLet's create a more practical request handler example that accepts JSON data and responds with a summary of the data.
// 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.
What are request handlers in the context of Node.js?
What are the `request` and `response` objects in the context of request handlers?