0
0
Node.jsframework~30 mins

Request validation in Node.js - Mini Project: Build & Apply

Choose your learning style9 modes available
Request Validation in Node.js
📖 Scenario: You are building a simple Node.js server that accepts user data through a POST request. To keep your server safe and reliable, you need to check that the data sent by users is correct before using it.
🎯 Goal: Build a Node.js server that validates incoming request data to ensure it has the correct fields and types before processing.
📋 What You'll Learn
Create an object representing user data with specific fields
Add a configuration variable to define required fields
Write a function to validate the user data against the required fields
Integrate the validation function into a simple HTTP server request handler
💡 Why This Matters
🌍 Real World
Validating user input is essential to prevent errors and security issues in web servers and APIs.
💼 Career
Backend developers often write validation logic to ensure data integrity before processing or storing user data.
Progress0 / 4 steps
1
Create user data object
Create a constant called userData with these exact properties: name set to "Alice", email set to "alice@example.com", and age set to 30.
Node.js
Need a hint?

Use const to create an object with the exact keys and values.

2
Define required fields array
Create a constant called requiredFields that is an array containing the strings "name", "email", and "age".
Node.js
Need a hint?

Use an array literal with the exact strings inside.

3
Write validation function
Write a function called validateUserData that takes one parameter data. Inside, use a for loop with variable field to iterate over requiredFields. For each field, check if data[field] is undefined. If so, return false. After the loop, return true.
Node.js
Need a hint?

Use a for...of loop and check each required field in the data object.

4
Use validation in HTTP server
Create a simple HTTP server using Node.js http module. Inside the request handler, call validateUserData(userData). If it returns true, set response status code to 200 and end with "Valid data". Otherwise, set status code to 400 and end with "Invalid data". Export the server as server.
Node.js
Need a hint?

Use http.createServer and call validateUserData inside the request handler.