Request body transformation helps change the data sent by a user before your app uses it. This makes it easier to work with or safe to store.
Request body transformation in Express
app.use(express.json()); app.post('/path', (req, res) => { const transformedBody = transformFunction(req.body); // use transformedBody for your logic res.send(transformedBody); });
Use express.json() middleware to parse JSON request bodies first.
Transformation happens inside the route handler after parsing.
app.post('/user', (req, res) => {
const body = req.body;
body.name = body.name.trim();
res.send(body);
});app.post('/date', (req, res) => {
const body = req.body;
body.date = new Date(body.date);
res.send(body);
});app.post('/clean', (req, res) => {
const { password, ...safeData } = req.body;
res.send(safeData);
});This Express app listens for POST requests at /transform. It changes the request body by trimming the name, turning age into a number, and converting the joined date string into a Date object. Then it sends back the transformed data as JSON.
import express from 'express'; const app = express(); app.use(express.json()); app.post('/transform', (req, res) => { const { name, age, joined } = req.body; // Transform: trim name, convert age to number, convert joined to Date const transformed = { name: name.trim(), age: Number(age), joined: new Date(joined) }; res.json(transformed); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Always parse JSON body with express.json() before transforming.
Be careful with data types; converting strings to numbers or dates helps avoid bugs.
Transformation can also help improve security by removing unwanted fields.
Request body transformation changes incoming data to a better format.
It happens after parsing the JSON body in Express.
Use it to clean, convert, or remove data before using it in your app.
Practice
Solution
Step 1: Understand request body transformation
Request body transformation modifies the data received from the client to a better format for the app.Step 2: Identify the main purpose
This process happens after parsing and helps clean or convert data before use.Final Answer:
To change incoming data into a more useful format before using it -> Option CQuick Check:
Request body transformation = change data format [OK]
- Confusing transformation with sending response
- Mixing transformation with error handling
- Thinking it sets HTTP headers
Solution
Step 1: Identify JSON parsing middleware
express.json() parses incoming JSON request bodies into JavaScript objects.Step 2: Confirm other options
express.urlencoded() parses URL-encoded data, express.static() serves files, express.raw() parses raw buffer data.Final Answer:
express.json() -> Option DQuick Check:
JSON body parser = express.json() [OK]
- Using express.urlencoded() for JSON data
- Confusing express.static() as parser
- Not parsing body before transformation
req.body.age after transformation?
app.use(express.json());
app.post('/user', (req, res) => {
req.body.age = Number(req.body.age);
res.send(req.body);
});
If the client sends JSON {"age": "30"}?Solution
Step 1: Parse JSON body
express.json() converts the JSON string {"age": "30"} into an object with age as string "30".Step 2: Transform age to number
req.body.age = Number(req.body.age) converts the string "30" to the number 30.Final Answer:
30 (number) -> Option AQuick Check:
Number("30") = 30 [OK]
- Assuming age stays a string
- Thinking Number("30") returns NaN
- Confusing undefined with missing property
app.use(express.json());
app.post('/data', (req, res) => {
req.body.count = parseInt(req.body.count);
if (!req.body.count) {
res.status(400).send('Count required');
}
res.send(req.body);
});Solution
Step 1: Understand parseInt and check
parseInt converts strings to numbers; 0 is falsy in JavaScript.Step 2: Analyze the if condition
The condition '!req.body.count' treats 0 as false, wrongly triggering the error for count=0.Final Answer:
The check '!req.body.count' fails when count is 0 -> Option BQuick Check:
Falsy check fails for 0 count [OK]
- Assuming parseInt is wrong here
- Missing express.json() middleware
- Calling res.send before res.status
Solution
Step 1: Check middleware and iteration
express.json() is needed to parse JSON bodies; for..in loops over keys correctly.Step 2: Validate transformation logic
app.use(express.json()); app.post('/transform', (req, res) => { for (const key in req.body) { if (req.body[key] === '') delete req.body[key]; else if (!isNaN(req.body[key])) req.body[key] = Number(req.body[key]); } res.send(req.body); }); deletes keys with empty strings and converts numeric strings to numbers using !isNaN check.Step 3: Compare other options
app.use(express.json()); app.post('/transform', (req, res) => { Object.keys(req.body).forEach(key => { if (req.body[key] === '') req.body[key] = null; else if (typeof req.body[key] === 'string') req.body[key] = parseInt(req.body[key]); }); res.send(req.body); }); sets empty strings to null and always parses strings with parseInt (may convert non-numeric wrongly). app.use(express.urlencoded()); app.post('/transform', (req, res) => { for (const key in req.body) { if (req.body[key] === '') delete req.body[key]; else if (!isNaN(req.body[key])) req.body[key] = Number(req.body[key]); } res.send(req.body); }); uses express.urlencoded() which is wrong for JSON. app.use(express.json()); app.post('/transform', (req, res) => { for (const key in req.body) { if (req.body[key] === '') req.body[key] = undefined; else if (isNaN(req.body[key])) req.body[key] = Number(req.body[key]); } res.send(req.body); }); wrongly converts non-numeric strings to numbers.Final Answer:
app.use(express.json()); app.post('/transform', (req, res) => { for (const key in req.body) { if (req.body[key] === '') delete req.body[key]; else if (!isNaN(req.body[key])) req.body[key] = Number(req.body[key]); } res.send(req.body); }); -> Option AQuick Check:
Delete empty and convert numeric strings = app.use(express.json()); app.post('/transform', (req, res) => { for (const key in req.body) { if (req.body[key] === '') delete req.body[key]; else if (!isNaN(req.body[key])) req.body[key] = Number(req.body[key]); } res.send(req.body); }); [OK]
- Using wrong middleware for JSON
- Setting empty strings to null instead of deleting
- Converting non-numeric strings to numbers
Ready to prove it?
Pass the test and this pattern moves unknown
