0
0
Node.jsframework~10 mins

Input validation and sanitization in Node.js - Interactive Code Practice

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

Complete the code to import the Express framework.

Node.js
const express = require('[1]');
Drag options to blanks, or click blank then click option'
Aexpress
Bhttp
Cfs
Dpath
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'http' instead of 'express' to import the framework.
2fill in blank
medium

Complete the code to use the express.json() middleware for parsing JSON input.

Node.js
app.use([1]());
Drag options to blanks, or click blank then click option'
AcookieParser
Bexpress.json
CbodyParser.text
Dexpress.urlencoded
Attempts:
3 left
💡 Hint
Common Mistakes
Using express.urlencoded() which parses URL-encoded data instead of JSON.
3fill in blank
hard

Fix the error in the validation code to check if the input 'age' is a number.

Node.js
if (typeof [1] !== 'number') {
  res.status(400).send('Age must be a number');
}
Drag options to blanks, or click blank then click option'
Areq.body.age
Breq.params.age
Creq.query.age
Dreq.age
Attempts:
3 left
💡 Hint
Common Mistakes
Using req.params.age or req.query.age when input is sent in JSON body.
4fill in blank
hard

Fill both blanks to sanitize and validate a username input using the 'validator' library.

Node.js
const sanitizedUsername = validator.[1](req.body.username);
if (!validator.[2](sanitizedUsername)) {
  res.status(400).send('Invalid username');
}
Drag options to blanks, or click blank then click option'
Aescape
BisEmail
CisAlphanumeric
Dtrim
Attempts:
3 left
💡 Hint
Common Mistakes
Using isEmail() to validate username which is incorrect.
5fill in blank
hard

Fill all three blanks to create a middleware that validates and sanitizes an email input.

Node.js
function validateEmail(req, res, next) {
  const email = validator.[1](req.body.email);
  if (!validator.[2](email)) {
    return res.status(400).send('Invalid email');
  }
  req.body.email = email[3]();
  next();
}
Drag options to blanks, or click blank then click option'
AnormalizeEmail
BisEmail
Ctrim
Descape
Attempts:
3 left
💡 Hint
Common Mistakes
Using escape() on email which can break the format.