Lab08 - Express
Lab08 - Express
Objective:
This lab introduces students to the core concepts of the Express.js framework. The focus is on
setting up a basic Express server, configuring routes, and understanding how to handle HTTP
requests and responses. Students will learn how to create simple endpoints, use middleware,
and manage server functionality.
Activity Outcomes:
Solution:
// index.js
const express = require('express');
const app = express();
const port = 3000;
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
Run the server with node index.js, then visit http://localhost:3000 in your browser to see the response.
// index.js
app.get('/', (req, res) => {
res.send('Hello, Express!');
});
1. Add middleware that logs each incoming request to the console, showing the HTTP method
and the URL.
2. The middleware should run before any routes are processed.
3. Test the server by visiting different routes and see the logs in the console.
// index.js
app.use((req, res, next) => {
console.log(`Received a ${req.method} request at ${req.url}`);
next(); // Pass control to the nex t middleware or route handler
});
Every request made to the server will log something like Received a GET request at / in the console.
// index.js
app.use(express.urlencoded({ extended: true })); // Middleware to parse form data
You can test this route by sending a POST request from Postman or through an HTML form.
Test the route by visiting http://localhost:3000/error, which should return a JSON response with the
error message.
2) Graded Lab Tasks
You are required to build a simple Express server that handles multiple routes with dynamic
responses. Specifically, you need to:
You are required to extend the Express server by adding the following functionality: