0
0
Expressframework~10 mins

Validating route params and query in Express - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to access the route parameter 'id' in Express.

Express
app.get('/user/:id', (req, res) => {
  const userId = req.params.[1];
  res.send(`User ID is ${userId}`);
});
Drag options to blanks, or click blank then click option'
Abody
Bquery
Cid
Dparam
Attempts:
3 left
💡 Hint
Common Mistakes
Using req.query instead of req.params for route parameters.
Trying to access req.param instead of req.params.
2fill in blank
medium

Complete the code to access the query parameter 'search' in Express.

Express
app.get('/items', (req, res) => {
  const searchTerm = req.[1].search;
  res.send(`Search term is ${searchTerm}`);
});
Drag options to blanks, or click blank then click option'
Aquery
Bparams
Cbody
Dheaders
Attempts:
3 left
💡 Hint
Common Mistakes
Using req.params instead of req.query for query parameters.
Trying to access query parameters from req.body.
3fill in blank
hard

Fix the error in validating that the 'id' route parameter is a number.

Express
app.get('/product/:id', (req, res) => {
  const id = req.params.[1];
  if (isNaN(id)) {
    return res.status(400).send('Invalid ID');
  }
  res.send(`Product ID is ${id}`);
});
Drag options to blanks, or click blank then click option'
Aparams
BproductId
Cquery
Did
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong parameter name that does not exist in the route.
Trying to get the parameter from req.query instead of req.params.
4fill in blank
hard

Fill both blanks to validate that the 'page' query parameter is a positive integer.

Express
app.get('/list', (req, res) => {
  const page = parseInt(req.[1].[2], 10);
  if (isNaN(page) || page < 1) {
    return res.status(400).send('Invalid page number');
  }
  res.send(`Page number is ${page}`);
});
Drag options to blanks, or click blank then click option'
Aquery
Bparams
Cpage
Dbody
Attempts:
3 left
💡 Hint
Common Mistakes
Using req.params instead of req.query for query parameters.
Using a wrong parameter name.
5fill in blank
hard

Fill all three blanks to validate that the 'userId' route param is numeric and 'sort' query param is either 'asc' or 'desc'.

Express
app.get('/users/:userId', (req, res) => {
  const userId = req.params.[1];
  const sort = req.query.[2];
  if (isNaN(userId)) {
    return res.status(400).send('Invalid user ID');
  }
  if (sort !== 'asc' && sort !== [3]) {
    return res.status(400).send('Invalid sort order');
  }
  res.send(`User ID: ${userId}, Sort: ${sort}`);
});
Drag options to blanks, or click blank then click option'
AuserId
Bsort
C'desc'
D'asc'
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up route params and query params.
Not checking both allowed sort values.
Using quotes incorrectly around string values.