0% found this document useful (0 votes)
18 views7 pages

Server-Side Hands-On Lab Manual

Uploaded by

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

Server-Side Hands-On Lab Manual

Uploaded by

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

Server-side Hands-on Lab Manual

Step 1: Create a Project Folder

Instruction: Create a folder named Mern_Project from your VS Code editor.

Explanation: This will be the root directory for your project. Organizing your project files in a structured
folder is crucial as it makes the management of files, configurations, and modules easier.

Step 2: Create a Server Subfolder

Instruction: Inside Mern_Project, create a subfolder called Server.

Explanation: This Server folder will contain all server-related files. Separating client and server code,
especially in full-stack projects like MERN, helps manage back-end and front-end operations effectively.

Step 3: Initialize package.json

Instruction: Open the terminal inside the Server folder and type npm init -y.

Explanation: The npm init -y command creates a package.json file with default values. This file manages
the server’s configurations, dependencies, and scripts, serving as the central management file for the
Node.js project.

Step 4: Install Express.js

Instruction: In the terminal, run npm i express to install Express.js.

Explanation: Express.js is a minimalist framework for building back-end applications on Node.js. It


simplifies tasks like routing, handling HTTP requests, and serving static files.

Step 5: Create server.js

Instruction: Create a file named server.js in the Server folder.

Explanation: The server.js file will act as the main entry point for your server. It will contain the server
configuration and setup code for handling incoming requests and responses.

Step 6: Write Initial Server Code

Instruction: Add the following code to server.js:


const express = require("express");

const app = express();

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

res.status(200).send("Welcome to Server side scripting with Node & Express");

});

const PORT = 5000;

app.listen(PORT, () => {

console.log(`Server is running at PORT: ${PORT}`);

});

Explanation: Here, you’re setting up a basic server using Express. This code:

• Imports Express,

• Initializes an Express app,

• Sets up a simple route (/) that sends a response message, and

• Listens on port 5000, logging a confirmation message once the server is running.

Step 7: Run the Server

Instruction: Open the terminal and type npm start or node server.js, then open your browser at
http://localhost:5000/.

Explanation: Running the server lets you access the app in a browser, displaying the configured message
to confirm the server is working.

Step 8: Add Additional Routes

Instruction: Add another route in server.js:

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

res.send("This is my About section");

});
Explanation: Adding multiple routes enables your server to handle various endpoints. Here, you add an
/about route, which will show a different message when accessed at http://localhost:5000/about.

Step 9: Install Nodemon

Instruction: Run npm i -g nodemon in the terminal.

Explanation: Nodemon automatically restarts the server when code changes are detected, saving time
by eliminating the need to manually restart the server.

Step 10: Set Execution Policy (for Windows PowerShell)

Instruction: Open PowerShell as an administrator and type:

Set-ExecutionPolicy RemoteSigned -Scope CurrentUser

Press A to accept all.

Explanation: This setting allows PowerShell scripts to run locally without restrictions, which may be
necessary when working with Node.js and Nodemon on Windows.

Step 11: Run Server with Nodemon

Instruction: Type nodemon server.js in the terminal.

Explanation: With Nodemon active, the server will automatically update when you make changes to
your code.

Step 12: Set Up Routing Folder

Instruction: Create a folder named router inside Server and a file auth-routes.js inside it.

Explanation: Organizing routes in separate files keeps the server.js clean and modularizes the code,
which is especially useful as the project scales.

Step 13: Add Route Logic in auth-routes.js

Instruction: Write the following code in auth-routes.js:

const express = require("express");

const router = express.Router();


router.get("/", (req, res) => {

res.send("Welcome to Express Routing");

});

module.exports = router;

Explanation: This code sets up routing in Express. By defining routes in a separate file, you make the
code modular and easier to maintain.

Step 14: Import Router in server.js

Instruction: Add this code to server.js:

const router = require("./router/auth-routes");

app.use("/api/auth", router);

Explanation: The code uses the /api/auth prefix for all routes in auth-routes.js, allowing organized and
structured access to these endpoints.

Step 15: Alternate Routing Syntax

Instruction: Another way to define routes is:

router.route("/about").get((req, res) => {

res.send("This is About using Express Routing");

});

Explanation: Using router.route() is another clean way to chain HTTP methods to a route, especially
useful for defining multiple HTTP methods on the same path.

Step 16: Introduce Controllers

Instruction: Create a controllers folder inside Server and add auth-controller.js.

Explanation: Controllers handle business logic, keeping routes simple and adhering to the MVC (Model-
View-Controller) pattern. This separation is essential for cleaner and more maintainable code.

Step 17: Add Logic to auth-controller.js

Instruction: In auth-controller.js, add:

const home = async (req, res) => {


try {

res.status(200).send("Welcome to Express Routing using Controller");

} catch (error) {

console.log(error);

};

module.exports = home;

Explanation: This controller function sends a response for the home route. Controllers focus on handling
data and processing requests, leaving routes for request handling.

Step 18: Extend Controller Functions

Instruction: Add another function register in auth-controller.js:

const register = async (req, res) => {

try {

res.status(200).send("Welcome to Registration Page");

} catch (error) {

res.status(400).send({ msg: "Page not found" });

};

module.exports = { home, register };

Explanation: This extends the controller to handle a register route, allowing modular handling of
additional routes.

Step 19: Simplify Route Imports

Instruction: Update auth-router.js to:

const authcontroller = require("../controllers/auth-controller");

router.route("/").get(authcontroller.home);

router.route("/register").get(authcontroller.register);

Explanation: By using the controller directly, you keep the routing code clean and easy to follow.
Step 20: Install Postman and Test the Register Route

Instruction: Install Postman, a popular tool for testing APIs. Then, open Postman, set the request type to
GET, and enter the URL http://localhost:5000/api/auth/register. Click Send to see the output.

Explanation: Postman allows you to make HTTP requests to your API, simulating how your server will
respond. Here, testing the /register route helps ensure that your route is correctly set up and the server
returns the expected response.

Step 21: Test a POST Request in Postman

Instruction: In Postman:

• Set the request type to POST and enter the URL http://localhost:5000/api/auth/register.

• Go to the Headers tab, add a new key Content-Type with the value application/json.

• Go to the Body tab, select raw, and enter the following JSON data:

"email": "[email protected]",

"password": "123"

• Click Send to make the request.

Explanation: This step tests sending JSON data via a POST request. Setting Content-Type to
application/json tells the server that the data format is JSON, and the body contains the test email and
password data.

Step 22: Update auth-controller.js to Handle POST Data

Instruction: Modify the register function in auth-controller.js to handle incoming JSON data. Update the
function as follows:

// Logic for Registration

const register = async (req, res) => {

try {

console.log(req.body); // Log the incoming data for debugging

res.status(200).json({ msg: req.body });

} catch (error) {
res.status(400).send({ msg: "Page not found" });

};

module.exports = { home, register };

Explanation: This updated register function logs the request data (req.body) and responds with a JSON
object containing that data. This demonstrates that your server can accept and process JSON data in a
POST request.

Step 23: Add JSON Parsing Middleware in server.js

Instruction: Open server.js and add the following line at the top, before defining any routes:

app.use(express.json());

Explanation: express.json() is middleware that parses incoming JSON data, allowing you to access it via
req.body. Placing it at the start ensures all routes can handle JSON data, a common requirement for APIs.

Step 24: Update auth-routes.js to Test the POST Method

Instruction: In auth-routes.js, modify the route definition for /register as follows:

router.route("/register").post(authcontroller.register);

Explanation: This change updates the /register route to handle POST requests. Now, when you send a
POST request to /register, Express will invoke the register function in auth-controller.js, processing the
incoming JSON data.

Note: This completes the initial setup of a MERN server with routing, controllers, and testing. Each step
has built upon the previous one, establishing a clean and organized back-end structure.

You might also like