Homework & Coding Practice

Homework/Practice Coding Assignment (20-min)

Task 1: Include Middleware for Logging Requests

  1. Step 1: Modify app.js to include a middleware for logging:

    javascript코드 복사app.use((req, res, next) => {
        const time = new Date().toISOString();
        console.log(`[${time}] ${req.method} ${req.url}`);
        next();
    });
  2. 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

  1. 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!');
    });
  2. Step 2: Introduce a route that triggers an error:

    javascript코드 복사app.get('/error', (req, res) => {
        throw new Error('This is a simulated error.');
    });
  3. Step 3: Test the /error route using a browser or Postman. Verify the error message and log output.

Expected Outcomes

  1. Students can create a basic Express application with multiple routes.

  2. Middleware usage for logging and JSON parsing is understood.

  3. Homework reinforces error handling and logging in Express.

Last updated