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

Basic Express Server Setup Guide

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)
8 views5 pages

Basic Express Server Setup Guide

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

Lab 07 – Setting up a Basic Express Server

Objective:
This lab introduces students to the core concepts of the [Link] 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
[Link] 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 [Link] project using npm install express.


2. Create an [Link] 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:

// [Link]
const express = require('express');
const app = express();
const port = 3000;

[Link]('/', (req, res) => {


[Link]('Hello, Express!');
});

[Link](port, () => {
[Link](`Server running at [Link]
});

Run the server with node [Link], then visit [Link] 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.

// [Link]
[Link]('/', (req, res) => {
[Link]('Hello, Express!');
});

[Link]('/about', (req, res) => {


[Link]('About Us');
});

[Link]('/contact', (req, res) => {


[Link]('Contact Page');
});

Test the routes by visiting [Link] and [Link]

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.

// [Link]
[Link]((req, res, next) => {
[Link](`Received a ${[Link]} request at ${[Link]}`);
next(); // Pass control to the nex t middleware or route handler
});

[Link]('/', (req, res) => {


[Link]('Hello, Express!');
});

[Link]('/about', (req, res) => {


[Link]('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!".
// [Link]
[Link]('/greet', (req, res) => {
const name = [Link] || 'Stranger';
[Link](`Hello, ${name}!`);
});
Test by visiting [Link] 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 ([Link]()) to parse the form data.
3. Respond with a confirmation message containing the form data submitted.

// [Link]
[Link]([Link]({ extended: true })); // Middleware to parse form data

[Link]('/submit', (req, res) => {


const { name, email } = [Link];
[Link](`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.
// [Link]
[Link]('/error', (req, res) => {
throw new Error('Something went wrong!');
});

// Error handling middleware


[Link]((err, req, res, next) => {
[Link](500).json({ message: [Link] });
});

Test the route by visiting [Link] 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 contact@[Link]"
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 [Link]() 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]".

Common questions

Powered by AI

Middleware functions in Express can intercept and manipulate requests at different stages in the application lifecycle. By using a logging middleware, you can track every incoming request before the request reaches the route handlers. For example, 'app.use((req, res, next) => { console.log(`Received a ${req.method} request at ${req.url}`); next(); });' logs the HTTP method and requested URL, providing essential insight for debugging and monitoring . Middleware is versatile, supporting tasks from parsing request bodies to handling errors globally .

To set up a basic Express server, you should first install the Express package using npm ('npm install express'). Then, create an 'index.js' file where you require Express, create an app instance, and define routes. For instance, using 'app.get('/', (req, res) => { res.send('Hello, Express!'); });' you define a GET method for the root URL. Start the server using 'app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); });', where 'port' is a specified port number, such as 3000 .

Query parameters allow an Express application to generate dynamic responses based on client input. For instance, by setting up a route like '/greet' with 'app.get('/greet', (req, res) => { const name = req.query.name || 'Stranger'; res.send(`Hello, ${name}!`); });', the server can respond with a personalized greeting based on the query parameter 'name'. If the parameter is not provided, it defaults to 'Stranger'. This mechanism utilizes the 'req.query' object to access parameters, making responses flexible and tailored .

Managing POST requests in Express involves setting up routes to accept data submissions, often from forms. By using middleware such as 'express.urlencoded({ extended: true })', the application can parse incoming form data sent via POST requests. A route like '/submit' could be established to handle form submissions: 'app.post('/submit', (req, res) => { const { name, email } = req.body; res.send(`Form submitted! Name: ${name}, Email: ${email}`); });'. This setup allows the application to collect, process, and use submitted data dynamically .

Middleware enhances maintainability in Express applications by decoupling request handling concerns, such as authentication, logging, and error handling, from core business logic. By inserting middleware as reusable functions that can be applied consistently across different routes, developers can avoid repetitive code and update logic centrally. This modular approach allows for easy modification and extension of server functionality, improving adaptability to changing requirements or incremental features. Additionally, it clarifies the separation of concerns, making the codebase easier to understand and maintain .

Error-handling middleware in Express is crucial for capturing and managing errors across the application. It ensures that errors can be logged and a uniform response is delivered to the client, often in JSON format. In a demonstration, a route like '/error' could throw an error ('throw new Error('Something went wrong!');'), and an error-handling middleware, added with 'app.use', would catch this error and respond with 'res.status(500).json({ message: err.message });', providing client-side notification and debugging info .

Using middleware globally in an Express application, by applying it before any route definitions ('app.use'), ensures every request passes through this middleware, which can be beneficial for logging or security purposes. However, it may add unnecessary overhead for routes that don't require such processing. Conversely, applying middleware selectively, directly to specific routes (e.g., 'app.get('/route', middleware, handler)'), optimizes resource usage, ensuring that only relevant requests are processed with additional logic. This selective application allows for greater control and customization of route-specific behavior, enhancing the application's efficiency and responsiveness .

Express.js supports modular routing, which involves separating route logic into individual modules. This can be achieved using Express Router, which creates route handlers that can be mounted at specific paths. Modular routing enhances code readability and maintainability by compartmentalizing logical units of the application. It allows distinct files or modules to handle distinct routes, promoting a clean separation of concerns and making scaling or team collaboration more straightforward. This approach is advantageous as it prevents monolithic architecture, simplifies debugging, and streamlines testing [Not directly in the sources].

Setting up routes with identical paths but different HTTP methods enhances functionality by allowing the server to differentiate between various types of client requests on the same endpoint. For example, an Express server can define both 'app.get('/api/resource')' for fetching data and 'app.post('/api/resource')' for creating new data. This method-oriented routing supports RESTful design principles, providing a clear and intuitive way to organize and extend API capabilities, as each HTTP method typically represents specific actions (e.g., GET for retrieval, POST for creation, PUT for updates) [Not directly in the sources].

Express.js benefits include ease of use due to its minimalistic framework, flexibility in managing routes and middleware, and the ability to handle asynchronous operations efficiently with Node.js. It simplifies the creation of complex web servers and APIs through a vast ecosystem of middleware and packages. However, limitations include potential performance bottlenecks in CPU-intensive applications, as it is single-threaded, and a steeper learning curve for those unfamiliar with asynchronous JavaScript paradigms. Traditional server-side technologies, like Java's Spring, might offer more comprehensive tools for enterprise-level, CPU-intensive applications with in-built security and concurrency management features [Not directly in the sources].

You might also like