Understanding req helps you get information from the user's request. This lets your app respond correctly.
0
0
Why understanding req matters in Express
Introduction
When you want to read data sent by a user in a form.
When you need to check what URL or path the user asked for.
When you want to get details like cookies or headers from the user's browser.
When you want to handle different types of requests like GET or POST.
When you want to read query parameters from the URL.
Syntax
Express
app.get('/path', (req, res) => { // use req to get info const data = req.body; const query = req.query; const params = req.params; // respond res.send('Got your data'); });
req stands for request and holds all info sent by the user.
You use req.body for form data, req.query for URL queries, and req.params for URL parts.
Examples
Get a user ID from the URL part and send it back.
Express
app.get('/user/:id', (req, res) => { const userId = req.params.id; res.send(`User ID is ${userId}`); });
Read a search term from the URL query and respond with it.
Express
app.get('/search', (req, res) => { const term = req.query.term; res.send(`Search term is ${term}`); });
Read form data sent by POST and greet the user.
Express
app.post('/submit', (req, res) => { const name = req.body.name; res.send(`Hello, ${name}`); });
Sample Program
This program starts a server that listens for POST requests at /greet. It reads the name from the request body and replies with a greeting. If no name is sent, it says Hello, Guest!
Express
import express from 'express'; const app = express(); app.use(express.json()); app.post('/greet', (req, res) => { const name = req.body.name || 'Guest'; res.send(`Hello, ${name}!`); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
OutputSuccess
Important Notes
Always use middleware like express.json() to read JSON data from req.body.
Check if the data exists in req before using it to avoid errors.
Understanding req helps you make your app respond to what users send.
Summary
req holds all info sent by the user to your server.
You use req.params, req.query, and req.body to get different parts of the request.
Knowing how to use req helps your app understand and respond to users correctly.