0% found this document useful (0 votes)
2 views5 pages

Lab08 - Express

This document outlines a lab focused on setting up a basic Express.js server, covering core concepts such as routing, handling HTTP requests, and using middleware. Students will learn to create endpoints, manage server functionality, and handle both GET and POST requests. The lab includes activities for setting up routes, logging requests, sending dynamic responses, and implementing error handling, culminating in graded tasks that require building a functional Express server with specified features.

Uploaded by

amir.raza537918
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views5 pages

Lab08 - Express

This document outlines a lab focused on setting up a basic Express.js server, covering core concepts such as routing, handling HTTP requests, and using middleware. Students will learn to create endpoints, manage server functionality, and handle both GET and POST requests. The lab includes activities for setting up routes, logging requests, sending dynamic responses, and implementing error handling, culminating in graded tasks that require building a functional Express server with specified features.

Uploaded by

amir.raza537918
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

Lab 07 – Setting up a Basic Express Server

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:

By the end of this lab, students will be able to:

 Set up a basic Express server.


 Understand how to handle basic HTTP requests (GET, POST).
 Learn how to configure simple routes and send responses to the client.
 Get familiar with the Express application lifecycle and middleware.
1) Solved Lab Activites
Sr.No Allocated Time Level of Complexity CLO Mapping
1 10 Low CLO-5
2 10 Low CLO-5
3 10 Medium CLO-5
4 10 Medium CLO-5
5 10 Medium CLO-5
6 10 Medium CLO-5

Activity 1: Setup Express Server

1. Install Express in a Node.js project using npm install express.


2. Create an index.js file and set up the Express application.
3. Set up a route that responds to HTTP GET requests at the root URL / and sends "Hello,
Express!" as the response.
4. Start the server on port 3000.

Solution:

// index.js
const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {


res.send('Hello, Express!');
});

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.

Activity 2: Handling Different Routes

1. Add more routes to the Express server (e.g., /about, /contact).


2. Each route should return a different message or text, for example:

 /about should return "About Us"


 /contact should return "Contact Page"

3. Test each route by visiting them in the browser.

// index.js
app.get('/', (req, res) => {
res.send('Hello, Express!');
});

app.get('/about', (req, res) => {


res.send('About Us');
});

app.get('/contact', (req, res) => {


res.send('Contact Page');
});

Test the routes by visiting http://localhost:3000/about and http://localhost:3000/contact.

Activity 3: Using Middleware for Logging Requests


Learn how to use middleware in Express for logging.

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
});

app.get('/', (req, res) => {


res.send('Hello, Express!');
});

app.get('/about', (req, res) => {


res.send('About Us');
});

Every request made to the server will log something like Received a GET request at / in the console.

Activity 4: Sending Dynamic Responses


Learn how to use query parameters to send dynamic responses.

1. Create a route /greet that accepts a query parameter name.


2. If the query parameter is provided, send a greeting message using that name (e.g., "Hello,
[name]!").
3. If no query parameter is provided, send a default greeting message like "Hello, Stranger!".
// index.js
app.get('/greet', (req, res) => {
const name = req.query.name || 'Stranger';
res.send(`Hello, ${name}!`);
});
Test by visiting http://localhost:3000/greet?name=John in the browser to see "Hello, John!"

Activity 5: Handling POST Requests


Learn how to handle POST requests and capture form data.

1. Set up a basic route that listens to POST requests at /submit.


2. Use Express middleware (express.urlencoded()) to parse the form data.
3. Respond with a confirmation message containing the form data submitted.

// index.js
app.use(express.urlencoded({ extended: true })); // Middleware to parse form data

app.post('/submit', (req, res) => {


const { name, email } = req.body;
res.send(`Form submitted! Name: ${name}, Email: ${email}`);
});

You can test this route by sending a POST request from Postman or through an HTML form.

Activity 6: Simple Error Handling


Learn how to handle errors in Express.

1. Create a route /error that throws an error manually.


2. Add an error-handling middleware to catch the error and send a response with the error
message.
// index.js
app.get('/error', (req, res) => {
throw new Error('Something went wrong!');
});

// Error handling middleware


app.use((err, req, res, next) => {
res.status(500).json({ message: err.message });
});

Test the route by visiting http://localhost:3000/error, which should return a JSON response with the
error message.
2) Graded Lab Tasks

Lab Task 1: Create a Simple Express Server with Multiple Routes

You are required to build a simple Express server that handles multiple routes with dynamic
responses. Specifically, you need to:

1. Set up an Express server and make it listen on port 4000.


2. Create the following routes:
o / (Root route): Respond with "Welcome to the Express Server!"
o /about: Respond with "This is the About page."
o /contact: Respond with "Contact us at [email protected]"
3. For the /greet route, make it accept a query parameter name and return a personalized
greeting (e.g., "Hello, John!"). If no name is provided, return a default greeting, such
as "Hello, Stranger!".
4. Add a middleware to log all incoming requests. The log should display the HTTP
method and the route that was accessed.
5. Handle any potential errors by sending a JSON response with a message describing
the error.

Lab Task 2: Implement POST Request Handling and Dynamic Responses

You are required to extend the Express server by adding the following functionality:

1. Set up a POST route at /submit.


2. The /submit route should accept a form submission with two fields:
o name (string)
o email (string)
3. When the user submits the form, the server should respond with a confirmation
message that includes the name and email of the user.
4. To handle POST data, use the express.urlencoded() middleware to parse the form data.
5. Create a simple HTML form that sends a POST request to /submit with fields for name
and email. Ensure the form is styled in a basic way (e.g., center-aligned with simple
borders).
6. After submitting the form, the user should see a confirmation message like "Form
submitted! Name: [name], Email: [email]".

You might also like