Using Middleware and Enhancing APIs
Topic Outline (30-min)
Middleware Essentials:
Role and Execution Flow:
Middleware functions process requests before they reach the final route handler.
Middleware can modify
reqandresobjects or terminate the request-response cycle.
Built-in vs. Custom Middleware:
Built-in middleware includes
express.json()for parsing JSON.Custom middleware can be created for logging, authentication, etc.
javascript코드 복사app.use((req, res, next) => { console.log(`${req.method} ${req.url}`); next(); });
Static File Serving:
Use middleware to serve static files like HTML, CSS, and images.
javascript코드 복사app.use(express.static('public'));Place files in a folder named
public:/public/home.html/public/contact.html
Input Validation:
Validate request payloads using
express-validator:javascript코드 복사const { check, validationResult } = require('express-validator'); 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'); });
Last updated