In this section, we will learn how to access request variables in Express.js — including data from query strings, request bodies, and form submissions.
✅ Accessing Query Parameters (GET Request)
We’ll start by accessing query parameters using a GET
request.
UserRouter.ts
getRoutes() { this.router.get(‘/signup’, UserController.signup); }
UserController.ts
export class UserController { static signup(req, res, next) { res.send(req.query); // Access query parameters } }
Test via Postman:
Send a GET request to:
http://localhost:5000/api/user/[email protected]&password=testPassword
Response::
{ “email”: “[email protected]”, “password”: “testPassword” }
✅ This confirms we can access query parameters using req.query
.
✅ Accessing Body Data (POST Request)
For POST requests, data is usually sent through the request body using either:
-
x-www-form-urlencoded
(most common for forms) -
form-data
(used for file uploads, multipart) -
raw
(JSON, text, etc.)
✅ Update UserController.ts
:
export class UserController { static signup(req, res, next) { res.send(req.body); // Access POST body data } }
✅ Update UserRouter.ts
:
getRoutes() { this.router.post(‘/signup’, UserController.signup); }
⚠️ Problem: No Data Received?
If you send data via Postman (POST request using x-www-form-urlencoded
) and get no response or empty body, it’s because Express needs a body parser middleware.
✅ Installing Body Parser
Install the required packages:
npm i body-parser @types/body-parser
✅Configure Body Parser in Server.ts
import * as bodyParser from ‘body-parser’; setConfigurations() { this.connectMongoDb(); this.configureBodyParser(); // Must come before routes } configureBodyParser() { this.app.use(bodyParser.urlencoded({ extended: true })); }
🔍 Why
extended: true
?It allows parsing rich data (arrays/objects), not just strings.
✅ Test Again in Postman
-
URL:
http://localhost:5000/api/user/signup
-
Method: POST
-
Body → x-www-form-urlencoded:
Key | Value |
---|---|
[email protected] | |
password | testPassword |
Expected Response:
{ “email”: “[email protected]”, “password”: “testPassword” }
✅ Success! You’re now able to access POST data from the body.
🧠 Summary
Type | Where to Access | Example |
---|---|---|
Query Params | req.query |
/signup?email=...&password=... |
Body (POST) | req.body |
Sent via x-www-form-urlencoded |
Headers | req.headers |
Authorization , Content-Type , etc. |