Choose the best explanation for why input sanitization is important in Node.js apps.
Think about how attackers might try to harm your app through user input.
Input sanitization cleans user data to prevent harmful code or commands from running, protecting the app from attacks like SQL injection or cross-site scripting.
Consider the following code that validates and sanitizes an email input.
import validator from 'validator'; const input = ' user@example.com '; const isValid = validator.isEmail(input); const sanitized = validator.normalizeEmail(input); console.log(isValid, sanitized);
Check how 'validator.isEmail' and 'validator.normalizeEmail' handle spaces.
'validator.isEmail' returns false because it does not ignore surrounding spaces, treating them as invalid. 'validator.normalizeEmail' trims and normalizes the email, returning 'user@example.com'.
Review the code below that tries to validate usernames to be alphanumeric and 3-10 characters long.
function validateUsername(name) {
const regex = /^[a-zA-Z0-9]{3,10}$/;
return regex.test(name.trim());
}
console.log(validateUsername(' user1 '));
console.log(validateUsername('user_2'));Look carefully at the regex pattern and the test inputs.
The regex only allows letters and numbers, no underscores. 'user_2' contains an underscore, so it correctly fails validation. The function works as intended.
Choose the code snippet that safely sanitizes a string input to prevent XSS attacks.
const express = require('express'); const app = express(); app.use(express.json()); app.post('/submit', (req, res) => { const userInput = req.body.comment; // Sanitize userInput here res.send(`Received: ${sanitizedInput}`); });
Think about how to neutralize HTML tags to stop scripts from running.
Replacing '<' and '>' with their HTML entities prevents browsers from interpreting tags, stopping XSS. Removing only script tags (option D) can miss other harmful tags.
Analyze the middleware that validates a JSON body field 'age' to be a positive integer.
function validateAge(req, res, next) {
const age = req.body.age;
if (!Number.isInteger(age) || age <= 0) {
return res.status(400).json({ error: 'Age must be a positive integer' });
}
next();
}
// Usage in Express app
// app.use(express.json());
// app.post('/user', validateAge, (req, res) => res.send('User created'));Consider how Number.isInteger treats strings and missing values.
Number.isInteger returns false for strings and undefined. Age must be a positive integer number. Only numeric 25 passes; string '25', zero, or missing age fail.