Request and Response Handling
What is Request and Response Handling?
Request and response handling is the core functionality of any web server. It involves receiving incoming HTTP requests from clients (like web browsers), processing them, and sending back HTTP responses containing the requested data. This process forms the fundamental basis of how web applications communicate and interact.
Why is Request and Response Handling important?
Properly handling requests and responses is essential for:
- Delivering content: Serving web pages, images, and other resources to users.
- Responding to user interactions: Processing form submissions, handling user authentication, and updating databases.
- Providing a robust application: Implementing error handling, security measures, and proper response status codes to ensure a smooth user experience and prevent security vulnerabilities.
Request and Response Objects
Express.js provides convenient req
(request) and res
(response) objects that encapsulate all the information associated with an incoming HTTP request and the outgoing HTTP response, respectively.
req
object: Thereq
object contains details about the incoming request, including:req.method
: HTTP method (GET, POST, PUT, DELETE, etc.).req.url
: The requested URL path.req.query
: URL query parameters (e.g.,?id=123
).req.body
: The request body (for POST, PUT, etc.).req.headers
: HTTP headers sent by the client.req.ip
: The client’s IP address.req.params
: URL route parameters (e.g.,/users/:id
-req.params.id
).
res
object: Theres
object allows you to craft the response to send back to the client:res.send(data)
: Sends data (string, JSON, etc.) as the response body.res.status(code)
: Sets the HTTP status code (e.g., 200, 404).res.json(data)
: Sends JSON data as the response body.res.redirect(url)
: Redirects the client to a different URL.res.render(view, data)
: Renders a template file and sends it as the response.res.set(header, value)
: Sets a response header.
Middleware
Middleware functions are a powerful mechanism in Express.js to intercept requests and responses. They allow you to:
- Modify the request object (
req
) - Modify the response object (
res
) - Perform actions before or after request processing
Here’s a simple example:
app.use((req, res, next) => {
console.log('Time:', Date.now());
next();
});
This middleware logs the current timestamp for each incoming request.
Error Handling
Express.js provides a built-in mechanism for handling errors that occur during request processing. You can use middleware to catch errors and send appropriate responses:
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
This middleware logs the error stack trace and sends a 500 error response to the client.
Reference
Top-Level Directory Explanations
bin/ - Contains scripts that can be executed directly, such as starting the application with node bin/www
.