Homework & Coding Practice
Homework/Practice Coding Assignment (20-min)
Task 1: Include Middleware for Logging Requests
Step 1: Modify
app.jsto include a middleware for logging:javascript코드 복사app.use((req, res, next) => { const time = new Date().toISOString(); console.log(`[${time}] ${req.method} ${req.url}`); next(); });Step 2: Restart the server and test by making requests to various routes. Observe the logs in the terminal.
Task 2: Handle Errors Using a Custom Error Handler
Step 1: Add an error-handling middleware at the end of the file:
javascript코드 복사app.use((err, req, res, next) => { console.error(err.stack); res.status(500).send('Something broke!'); });Step 2: Introduce a route that triggers an error:
javascript코드 복사app.get('/error', (req, res) => { throw new Error('This is a simulated error.'); });Step 3: Test the
/errorroute using a browser or Postman. Verify the error message and log output.
Expected Outcomes
Students can create a basic Express application with multiple routes.
Middleware usage for logging and JSON parsing is understood.
Homework reinforces error handling and logging in Express.
Last updated