Bird
Raised Fist0
Expressframework~20 mins

Request body transformation in Express - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Request Body Transformer
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this Express middleware?
Consider this Express middleware that modifies the request body before passing control to the next handler. What will be the value of req.body in the next middleware?
Express
app.use(express.json());
app.use((req, res, next) => {
  if (req.body && req.body.name) {
    req.body.name = req.body.name.trim().toUpperCase();
  }
  next();
});
app.post('/test', (req, res) => {
  res.json({ transformedName: req.body.name });
});
AIf sent {"name": " alice "}, response is {"transformedName": "alice"}
BIf sent {"name": " alice "}, response is {"transformedName": null}
CIf sent {"name": " alice "}, response is {"transformedName": " alice "}
DIf sent {"name": " alice "}, response is {"transformedName": "ALICE"}
Attempts:
2 left
💡 Hint
Think about how the middleware modifies the req.body.name before the final handler.
📝 Syntax
intermediate
2:00remaining
Which option correctly parses JSON body and adds a new field?
You want to parse JSON request bodies and add a new field timestamp with the current time before handling the request. Which code snippet correctly does this in Express?
A
app.use((req, res, next) => {
  req.body = JSON.parse(req.body);
  req.body.timestamp = Date.now();
  next();
});
B
app.use(express.json());
app.use((req, res, next) => {
  req.body.timestamp = Date.now();
  next();
});
C
app.use(express.urlencoded());
app.use((req, res, next) => {
  req.body.timestamp = Date.now();
  next();
});
D
;)}
;)(txen  
;)(won.etaD = pmatsemit.ydob.qer  
{ >= )txen ,ser ,qer((esu.ppa
;))(nosj.sserpxe(esu.ppa
Attempts:
2 left
💡 Hint
Remember to parse JSON before accessing req.body as an object.
🔧 Debug
advanced
2:00remaining
Why does this middleware not modify the request body as expected?
This middleware tries to uppercase a field in the request body but the change is not reflected in the final handler. Why?
Express
app.use((req, res, next) => {
  req.body.name.toUpperCase();
  next();
});
app.post('/user', (req, res) => {
  res.json({ name: req.body.name });
});
ABecause <code>res.json()</code> is called before the middleware.
BBecause <code>toUpperCase()</code> returns a new string but does not change <code>req.body.name</code> in place.
CBecause <code>next()</code> is called before modifying <code>req.body.name</code>.
DBecause <code>req.body</code> is undefined without JSON parsing middleware.
Attempts:
2 left
💡 Hint
Remember how string methods like toUpperCase() work in JavaScript.
❓ state_output
advanced
2:00remaining
What is the final value of req.body after this middleware chain?
Given these middlewares, what will req.body contain when the final handler runs?
Express
app.use(express.json());
app.use((req, res, next) => {
  req.body = { ...req.body, added: true };
  next();
});
app.use((req, res, next) => {
  delete req.body.removed;
  next();
});
app.post('/data', (req, res) => {
  res.json(req.body);
});
AIf sent {"name":"bob","removed":123}, response is {"added":true}
BIf sent {"name":"bob","removed":123}, response is {"name":"bob","removed":123,"added":true}
CIf sent {"name":"bob","removed":123}, response is {"name":"bob","added":true}
DIf sent {"name":"bob","removed":123}, response is {"name":"bob"}
Attempts:
2 left
💡 Hint
Look at how the object is copied and the removed property is deleted.
🧠 Conceptual
expert
3:00remaining
Which option best explains why modifying req.body directly in middleware can be risky?
In Express, why might directly changing req.body in middleware cause unexpected issues in later handlers or middleware?
ABecause <code>req.body</code> might be shared by other middleware expecting the original structure, so changes can break assumptions.
BBecause <code>req.body</code> is immutable and cannot be changed once parsed.
CBecause Express automatically resets <code>req.body</code> after each middleware.
DBecause modifying <code>req.body</code> requires asynchronous operations to be safe.
Attempts:
2 left
💡 Hint
Think about how middleware chains share the same request object.

Practice

(1/5)
1. What is the main purpose of request body transformation in Express?
easy
A. To send the response back to the client
B. To handle errors in the server
C. To change incoming data into a more useful format before using it
D. To set HTTP headers for the response

Solution

  1. Step 1: Understand request body transformation

    Request body transformation modifies the data received from the client to a better format for the app.
  2. Step 2: Identify the main purpose

    This process happens after parsing and helps clean or convert data before use.
  3. Final Answer:

    To change incoming data into a more useful format before using it -> Option C
  4. Quick Check:

    Request body transformation = change data format [OK]
Hint: Think: transform means change data format before use [OK]
Common Mistakes:
  • Confusing transformation with sending response
  • Mixing transformation with error handling
  • Thinking it sets HTTP headers
2. Which Express middleware is commonly used to parse JSON request bodies before transformation?
easy
A. express.urlencoded()
B. express.static()
C. express.raw()
D. express.json()

Solution

  1. Step 1: Identify JSON parsing middleware

    express.json() parses incoming JSON request bodies into JavaScript objects.
  2. Step 2: Confirm other options

    express.urlencoded() parses URL-encoded data, express.static() serves files, express.raw() parses raw buffer data.
  3. Final Answer:

    express.json() -> Option D
  4. Quick Check:

    JSON body parser = express.json() [OK]
Hint: Use express.json() to parse JSON bodies before transforming [OK]
Common Mistakes:
  • Using express.urlencoded() for JSON data
  • Confusing express.static() as parser
  • Not parsing body before transformation
3. Given this Express code, what will be the value of 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"}?
medium
A. 30 (number)
B. "30" (string)
C. NaN
D. undefined

Solution

  1. Step 1: Parse JSON body

    express.json() converts the JSON string {"age": "30"} into an object with age as string "30".
  2. Step 2: Transform age to number

    req.body.age = Number(req.body.age) converts the string "30" to the number 30.
  3. Final Answer:

    30 (number) -> Option A
  4. Quick Check:

    Number("30") = 30 [OK]
Hint: Number() converts string digits to number type [OK]
Common Mistakes:
  • Assuming age stays a string
  • Thinking Number("30") returns NaN
  • Confusing undefined with missing property
4. Identify the error in this Express request body transformation code:
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);
});
medium
A. parseInt should be replaced with Number
B. The check '!req.body.count' fails when count is 0
C. express.json() middleware is missing
D. res.send() should be called before res.status()

Solution

  1. Step 1: Understand parseInt and check

    parseInt converts strings to numbers; 0 is falsy in JavaScript.
  2. Step 2: Analyze the if condition

    The condition '!req.body.count' treats 0 as false, wrongly triggering the error for count=0.
  3. Final Answer:

    The check '!req.body.count' fails when count is 0 -> Option B
  4. Quick Check:

    Falsy check fails for 0 count [OK]
Hint: Check for 0 explicitly, not with '!value' [OK]
Common Mistakes:
  • Assuming parseInt is wrong here
  • Missing express.json() middleware
  • Calling res.send before res.status
5. You want to transform an incoming request body to remove any properties with empty strings and convert all numeric strings to numbers. Which code snippet correctly performs this transformation in Express?
hard
A. 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); });
B. 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); });
C. 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); });
D. 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); });

Solution

  1. Step 1: Check middleware and iteration

    express.json() is needed to parse JSON bodies; for..in loops over keys correctly.
  2. 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.
  3. 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.
  4. 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 A
  5. Quick 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]
Hint: Delete empty strings, convert numeric strings with !isNaN check [OK]
Common Mistakes:
  • Using wrong middleware for JSON
  • Setting empty strings to null instead of deleting
  • Converting non-numeric strings to numbers
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard