Handling Requests and Responses
In this section, we will delve deeper into how Express handles incoming requests and outgoing responses. Understanding these concepts will enable you to build more interactive and dynamic web applications.
Working with Request and Response Objects
Express provides two important objects for handling HTTP requests and responses: req
(request) and res
(response).
Request Object (req)
- Contains information about the HTTP request.
- Properties include
req.query
,req.params
,req.body
,req.headers
, and more.
Response Object (res)
- Used to send a response back to the client.
- Methods include
res.send()
,res.json()
,res.status()
,res.redirect()
, and more.
Example: Basic request and response handling:
// Importing the Express module
const express = require('express');
const app = express();
const port = 3000;
// Handling GET request at the root URL
app.get('/', (req, res) => {
res.send('Hello, World!'); // Sending a plain text response
});
// Handling GET request at the '/json' URL
app.get('/json', (req, res) => {
res.json({ message: 'Hello, World!' }); // Sending a JSON response
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});
Parsing Request Bodies
To handle incoming data in the body of a POST request, you need middleware to parse the request body. Express provides built-in middleware for this purpose.
Using
express.json()
Middlewarejavascript // Importing the Express module const express = require('express'); const app = express(); const port = 3000; // Middleware to parse JSON request bodies app.use(express.json()); // Handling POST request at the '/submit' URL app.post('/submit', (req, res) => { const { name, age } = req.body; // Extracting data from the request body res.send(`Name: ${name}, Age: ${age}`); }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}/`); });
Using
express.urlencoded()
Middlewarejavascript // Importing the Express module const express = require('express'); const app = express(); const port = 3000; // Middleware to parse URL-encoded request bodies app.use(express.urlencoded({ extended: true })); // Handling POST request at the '/submit' URL app.post('/submit', (req, res) => { const { name, age } = req.body; // Extracting data from the request body res.send(`Name: ${name}, Age: ${age}`); }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}/`); });
Handling Query Parameters and URL Parameters
Query Parameters: Accessed via
req.query
.javascript // Handling GET request with query parameters app.get('/search', (req, res) => { const { term, page } = req.query; // Extracting query parameters res.send(`Search Term: ${term}, Page: ${page}`); });
URL Parameters: Defined in the route path and accessed via
req.params
.javascript // Handling GET request with URL parameters app.get('/user/:id', (req, res) => { const { id } = req.params; // Extracting URL parameter res.send(`User ID: ${id}`); });
Sending Different Types of Responses
Express allows you to send various types of responses, such as plain text, JSON, and HTML.
Plain Text Response
javascript // Handling GET request and sending a plain text response app.get('/text', (req, res) => { res.send('This is a plain text response.'); });
JSON Response
javascript // Handling GET request and sending a JSON response app.get('/data', (req, res) => { res.json({ message: 'This is a JSON response.' }); });
HTML Response
javascript // Handling GET request and sending an HTML response app.get('/html', (req, res) => { res.send('<h1>This is an HTML response.</h1>'); });
Summary
In this section, we explored how to handle requests and responses in Express. You learned about the req
and res
objects, parsing request bodies, handling query and URL parameters, and sending different types of responses.