Student Activity

Student Activity (30-min)

Activity: Implement Middleware for Validation

Step-by-Step Procedure:

  1. Step 1: Set Up the Project:

    • Initialize the project and install dependencies:

      bash코드 복사mkdir middleware-api
      cd middleware-api
      npm init -y
      npm install express express-validator
  2. Step 2: Create app.js and Set Up Middleware:

    • Add a custom middleware for logging:

      javascript코드 복사const express = require('express');
      const { check, validationResult } = require('express-validator');
      const app = express();
      
      app.use(express.json());
      
      app.use((req, res, next) => {
          const time = new Date().toISOString();
          console.log(`[${time}] ${req.method} ${req.url}`);
          next();
      });
      
      const PORT = 3000;
      app.listen(PORT, () => console.log(`Server running on http://localhost:${PORT}`));
  3. Step 3: Add Validation Middleware:

    • Add a POST route for validating tasks:

      javascript코드 복사app.post('/tasks', [
          check('title').isString().notEmpty(),
          check('completed').isBoolean()
      ], (req, res) => {
          const errors = validationResult(req);
          if (!errors.isEmpty()) {
              return res.status(400).json({ errors: errors.array() });
          }
          res.send('Task is valid');
      });
  4. Step 4: Test the Application Using Postman:

    • Send a POST request to /tasks with a valid payload:

      json코드 복사{ "title": "Task 1", "completed": true }
    • Send another POST request with an invalid payload:

      json코드 복사{ "title": "", "completed": "yes" }
    • Observe the validation errors in the response.

Last updated