0% found this document useful (0 votes)
19 views18 pages

Express.js and Node.js Basics Guide

This document provides an introduction to Express.js and server-side basics with Node.js, covering installation, RESTful backend creation, route handling, middleware, and project structuring. It explains key concepts such as HTTP methods (GET, POST, PUT, DELETE), responses, and best practices for organizing a Node.js application. Additionally, it introduces tools like nodemon for automatic server restarts and emphasizes the importance of a consistent project structure for maintainability.

Uploaded by

devanshdalal18
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)
19 views18 pages

Express.js and Node.js Basics Guide

This document provides an introduction to Express.js and server-side basics with Node.js, covering installation, RESTful backend creation, route handling, middleware, and project structuring. It explains key concepts such as HTTP methods (GET, POST, PUT, DELETE), responses, and best practices for organizing a Node.js application. Additionally, it introduces tools like nodemon for automatic server restarts and emphasizes the importance of a consistent project structure for maintainability.

Uploaded by

devanshdalal18
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

Unit 2: Introduction to [Link] and Server-Side Basics with Node.

js

2.1 Introduction to [Link] and [Link]


2.1.1 Installing [Link] (v20+) and setting up Express server
2.1.2 Creating a RESTful backend using [Link]
2.1.3 Introduction to nodemon and project structuring
2.2 Handling Routes and HTTP Methods
2.2.1 Defining routes using GET, POST, PUT, DELETE
2.2.2 Sending responses and working with route/query parameters
2.2.3 Connecting routes to controller logic
2.3 Middleware and API Basics
2.3.1 Understanding middleware in Express
2.3.2 Using built-in and custom middleware (e.g., body-parser, static files)
2.3.3 Introduction to CORS and environment variables

2.1 Introduction to [Link] and [Link]

2.1.1 Installing [Link] (v20+) and Setting Up Express Server


What is [Link]?
Think of [Link] as a "JavaScript Engine outside the browser".
 Normally, JavaScript runs inside browsers like Chrome, Firefox, etc.
 But [Link] allows us to run JavaScript directly on a computer/server.
 It uses the V8 engine (the same engine Chrome uses).
 Built for server-side programming — meaning, it can handle files, databases, and APIs.
Why do we use [Link]?
Feature Description
Asynchronous Handles many clients at once without waiting for one request to finish
Fast Built on the V8 engine — very fast in executing code
JavaScript everywhere You can use the same language (JS) on frontend (React) and backend (Node)
Huge package support You get 1 million+ prebuilt packages via npm (Node Package Manager)
Installation Steps (Windows/Linux/Mac)
1. Go to 👉 [Link]
2. Download LTS (Long Term Support) version (e.g., v20.x)
3. Install with default options.
Verify installation:
node -v
npm -v
What is [Link]?
 [Link] is a framework built on top of [Link].
 [Link] is a web application framework built on top of [Link].
 It provides an easy and structured way to create server-side applications using JavaScript.
 Without Express, developers must write long, low-level HTTP server code using Node’s
built-in http module.
Express simplifies these tasks by offering built-in methods and clear structure.
 [Link] Simplifies Common Tasks
Task Description
Creating servers Quickly start an HTTP server using just a few lines of code.
Managing routes (URLs) Handle multiple URLs (like /home, /about, /api) easily.
Task Description
Handling requests and
Simplifies reading user input and sending data back.
responses
Apply functions (filters) that run before routes (for logging,
Using middleware
authentication, validation).
Makes it easy to create APIs using standard HTTP methods (GET,
Building RESTful APIs
POST, PUT, DELETE).
Installing [Link]
1. Create a project folder:
2. mkdir express-demo
3. cd express-demo
4. Initialize Node project:
5. npm init -y
It creates a [Link] file — a file that keeps record of your project and its dependencies.
6. Install Express:
7. npm install express

Create your first server


File: [Link]
// Step 1: Import express
const express = require('express');

// Step 2: Create an app


const app = express();

// Step 3: Define a route (GET request)


[Link]('/', (req, res) => {
[Link]('Welcome to [Link] Server!');
});

// Step 4: Start the server


[Link](3000, () => {
[Link]('Server is running at [Link]
});
Run the server(run using menu)
node [Link]
Now open browser → visit:
[Link]
You will see:
Welcome to [Link] Server!

2.1.2 Creating a RESTful Backend using [Link]


A RESTful backend exposes resources (for example, students, courses, orders) over HTTP using
standard HTTP methods. REST (Representational State Transfer) is an architectural style, not a strict
protocol — it emphasizes uniform interfaces, statelessness, and resource-orientation.
Key ideas:
 Resources are nouns (e.g., /students, /students/42).
 Actions are HTTP methods (GET/POST/PUT/PATCH/DELETE).
 The server returns representations (usually JSON) of resources.
 RESTful APIs should be predictable, discoverable, and use standard HTTP features correctly
(status codes, headers, caching).

Core HTTP methods and semantics


 GET — retrieve representation(s) of a resource.
o Safe (should not change server state) and idempotent.
o Example: GET /api/students (list), GET /api/students/42 (single).
 POST — create a new resource under the target collection.
o Not idempotent (multiple identical POSTs create multiple resources).
o Example: POST /api/students with JSON body → returns 201 Created and usually
Location header pointing to new resource.
 PUT — replace an existing resource (full update).
o Idempotent: calling it multiple times with same body yields same state.
o Example: PUT /api/students/42 with full student object.
 PATCH — partially modify a resource (partial update).
o Not necessarily idempotent unless implemented that way. Use when only some
fields change.
 DELETE — remove a resource.
o Idempotent: deleting a non-existing resource should still return an appropriate
status (204 or 404 based on your choice).
Understanding idempotency and safety helps design reliable clients and servers (retries, caching).
URIs and resource modelling
Good URI practices:
 Use plural nouns for collections: /students, /courses.
 Nest for hierarchy only when it makes sense: /students/42/grades.
 Keep URIs stable; version APIs via URL (/v1/students) or header (Accept).
 Avoid verbs in URIs (/getStudents is poor design).
Example:
const express = require('express');
const app = express();
[Link]([Link]()); // Middleware to parse JSON

let students = [
{ id: 1, name: 'Amit', course: 'BCA' },
{ id: 2, name: 'Riya', course: 'MCA' }
];

// READ all students


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

// CREATE a new student


[Link]('/students', (req, res) => {
const newStudent = [Link];
[Link](newStudent);
[Link](201).json(newStudent);
});

// UPDATE a student by ID
[Link]('/students/:id', (req, res) => {
const id = parseInt([Link]);
const student = [Link](s => [Link] === id);
if (student) {
[Link] = [Link];
[Link] = [Link];
[Link](student);
} else {
[Link](404).send('Student not found');
}
});

// DELETE a student
[Link]('/students/:id', (req, res) => {
const id = parseInt([Link]);
students = [Link](s => [Link] !== id);
[Link]('Student deleted successfully');
});

// Start server
[Link](3000, () => {
[Link]('Server is running at [Link]
});

2.1.3 Introduction to Nodemon and Project Structuring


Every time you make a change, you have to stop and restart the server manually. nodemon
automatically restarts your [Link] app whenever you modify files.
Install nodemon:
npm install -g nodemon
Run with nodemon:
nodemon [Link]
Now, any code change → nodemon restarts automatically.
As a developer -> for run using “npm run dev” 
Add in [Link] file
"scripts": {
"start": "node [Link]",
"dev": "nodemon [Link]"
}

Project Structure for Scalable Apps


A consistent project structure makes your codebase more predictable and easier to navigate for
anyone working on it. It separates concerns, helping to manage code complexity and improve long-
term maintenance.
Example [Link] project structure
Here is a typical project structure for a [Link] web application, which separates code by function.
my-express-project/
├── node_modules/ # Contains installed npm dependencies.
├── [Link] # Lists project dependencies and scripts.
├── .env # Stores environment-specific configuration variables (e.g., database URLs).
├── .gitignore # Specifies which files Git should ignore (e.g., node_modules/, .env).
├── [Link] # The application's entry point.
├── app/ # Contains the main application logic.
│ ├── controllers/ # Handles incoming requests and sends responses.
│ ├── models/ # Defines data structures and interacts with the database.
│ ├── routes/ # Defines API endpoints and links them to controllers.
│ └── views/ # Stores template files for rendering pages.
├── public/ # Serves static files like CSS, JavaScript, and images.
│ ├── css/
│ ├── js/
│ └── images/
├── tests/ # Contains all unit and integration tests.
└── [Link] # Provides information and documentation for the project.
Best practices for structuring
 Separate code by purpose: Keep your business logic (controllers), data handling (models),
and routing logic (routes) in separate, designated folders.
 Use a src directory: For larger projects, wrapping your core application logic in a src folder
clearly separates your source code from other files like configuration or public assets.
 Utilize .env for secrets: Never hard-code sensitive info like API keys, database URIs, or JWT
secrets.
o PORT=3000
DB_URL=mongodb+srv://username:password@[Link]/studentDB
SECRET_KEY=mySuperSecretKey
 Organize static assets: Place client-side files (HTML, CSS, JS, images) inside a dedicated
public directory.

2.2 Handling Routes and HTTP Methods


A route in Express defines how the server responds to a specific HTTP request method and URL
path.
Each route consists of:
[Link](PATH, HANDLER)
Where:
 METHOD → HTTP method (GET, POST, PUT, DELETE)
 PATH → URL endpoint (e.g. /students)
 HANDLER → Function that executes when route is matched
Example:
[Link]('/students', (req, res) => {
[Link](students);
});
2.2.1 Defining Routes using GET, POST, PUT, DELETE
1. GET Method — Read / Retrieve Data
 Used to fetch or retrieve data from the server. It does not modify data on the server.
 Data is sent in the URL (query string).
 It is safe and idempotent (multiple requests return the same result).
Example in Express
[Link]('/students', (req, res) => {
[Link]([
{ id: 1, name: 'Amit', course: 'BCA' },
{ id: 2, name: 'Riya', course: 'MCA' }
]);
});
Run
GET [Link]
2. POST Method — Create New Data
 Used to add new data to the server.
 Data is sent in the request body.
 Used when adding new records.
 It is not idempotent (sending the same POST twice creates two entries).
Example in Express
[Link]('/students', (req, res) => {
const newStudent = [Link];
[Link](201).json({ message: 'Student added', data: newStudent });
});
Example Request
POST URL:
[Link]
Request Body (JSON):
{
"id": 3,
"name": "Meera",
"course": "[Link]"
}
Example Output
{
"message": "Student added",
"data": { "id": 3, "name": "Meera", "course": "[Link]" }
}
3. PUT Method — Update Existing Data
 Used to update or replace existing data on the server.
 Usually includes an ID in the URL (e.g., /students/:id).
 The request body contains the new version of the data.
 It is idempotent — sending the same request multiple times has the same result.
Example in Express
[Link]('/students/:id', (req, res) => {
const id = parseInt([Link]);
const updatedData = [Link];
[Link]({ message: `Student ${id} updated`, data: updatedData });
});
Example Request
PUT URL:
[Link]
Request Body (JSON):
{
"name": "Riya Sharma",
"course": "MCA"
}
Example Output
{
"message": "Student 2 updated",
"data": { "name": "Riya Sharma", "course": "MCA" }
}
4. DELETE Method — Remove Data
 Used to delete or remove data from the server.
 Often used with an ID parameter in the URL.
 It is idempotent — deleting the same resource multiple times has no further effect.
Example in Express
[Link]('/students/:id', (req, res) => {
const id = parseInt([Link]);
[Link]({ message: `Student ${id} deleted successfully` });
});
Example Request
DELETE [Link]
Example Output
{ "message": "Student 2 deleted successfully" }

2.2.2 Sending Responses and Working with Parameters


[Link]. Sending Responses in Express
Every Express route sends a response back to the client using the res (response) object.
This response can be text, JSON data, HTML, or a status code.

Common Response Methods


Method Description Example
Sends a simple text, HTML, array, or object
[Link]() [Link]("Hello World")
response
[Link]() Sends a JSON-formatted response [Link]({ id: 1, name: "Amit" })
[Link]() Sets HTTP status code (can be chained) [Link](404).send("Not Found")
Sends a response with status code and
[Link]() [Link](200)
message
[Link]() Redirects the client to another URL [Link]('/home')
[Link]() Sends a file for download [Link]('[Link]')
[Link](__dirname +
[Link]() Sends a specific file
'/[Link]')

Example:
[Link]('/students', (req, res) => {
const students = [
{ id: 1, name: 'Amit', course: 'BCA' },
{ id: 2, name: 'Riya', course: 'MCA' }
];
[Link](200).json(students);
});
Output (Browser or Postman):
[
{ "id": 1, "name": "Amit", "course": "BCA" },
{ "id": 2, "name": "Riya", "course": "MCA" }
]
HTTP Status Codes
HTTP status codes indicate the result of a client’s request.
Code Meaning Typical Use
200 OK Request succeeded
201 Created Resource created successfully (POST)
204 No Content Success, but no data to send (DELETE)
Code Meaning Typical Use
400 Bad Request Client sent invalid data
404 Not Found Resource not found
500 Internal Server Error Something failed on the server
[Link]. Working with Parameters
Express allows you to send information through the URL, query string, or request body.
(A) Route Parameters — [Link]
 Values that are part of the URL path, identified by a colon : in the route.
 Used for identifying specific resources, like /students/10, /books/22, etc.
Example Route:
[Link]('/students/:id', (req, res) => {
const id = [Link];
[Link](`Student ID is ${id}`);
});
Request:
GET [Link]
Output:
Student ID is 5
(B) Query Parameters — [Link]
 Key-value pairs that appear after a question mark (?) in the URL.
 Often used for filtering, pagination or sorting data.
Example Route:
[Link]('/students', (req, res) => {
const course = [Link];
const year = [Link];
[Link](`Filter by course: ${course}, year: ${year}`);
});
Request:
GET [Link]
Output:
Filter by course: MCA, year: 2025
(C) Request Body — [Link]
 Data sent by the client (in POST or PUT requests) is stored in the request body.
 To read it, use the middleware [Link]().
 Used for creating or updating records.
Example Route:
[Link]([Link]());
[Link]('/students', (req, res) => {
const newStudent = [Link];
[Link](201).json({ message: 'Student added', data: newStudent });
});
Request Body (in Postman):
{
"id": 3,
"name": "Meera",
"course": "[Link]"
}
Output:
{
"message": "Student added",
"data": { "id": 3, "name": "Meera", "course": "[Link]" }
}
4. Combining Parameters
You can use route, query, and body parameters together.
Example:
[Link]('/students/:id', (req, res) => {
const id = [Link]; // route parameter
const updatedData = [Link]; // body data
const notify = [Link]; // query parameter

[Link]({
message: `Student ${id} updated`,
notify,
updatedData
});
});
Request:
PUT [Link]
Body: { "name": "Riya Sharma", "course": "MCA" }
Output:
{
"message": "Student 2 updated",
"notify": "yes",
"updatedData": { "name": "Riya Sharma", "course": "MCA" }
}
5. Example Program (Complete)
[Link]
const express = require('express');
const app = express();

[Link]([Link]());

// Route parameters
[Link]('/students/:id', (req, res) => {
[Link](`Fetching student with ID: ${[Link]}`);
});

// Query parameters
[Link]('/students', (req, res) => {
[Link](`Filtering students by course: ${[Link]}`);
});

// Request body
[Link]('/students', (req, res) => {
[Link](201).json({ message: 'Student added', data: [Link] });
});

// Start server
[Link](3000, () => [Link]('Server running on port 3000'));
Run:
node [Link]

2.2.3 Connecting Routes to Controller Logic


 Define routes → which URL should respond to which HTTP method (GET, POST, etc.).
A route tells your Express app:
 Which URL to listen to (like /students)
 Which HTTP method to use (GET, POST, PUT, DELETE)
 And what should happen when that request comes in
Example:
[Link]('/students', ...); // For fetching data
[Link]('/students', ...); // For saving new data
 Define controllers → what should happen when a request comes to that route (fetch data,
save data, etc.).
A controller contains the logic — the code that runs when the route is called.
It can:
o Fetch data from a database
o Save or update data
o Delete data
o Send a response back to the client
Example:
[Link] = (req, res) => {
[Link]("All students list");
};
[Link] = (req, res) => {
[Link]("New student added");
};
 Then, connect the two — so the right controller runs when a user visits that route.

Keep logic separate for maintainability.


📁 routes/[Link]
const express = require("express");
const router = [Link]();

// Import controller
const studentController = require("../controllers/studentController");

// Define routes and connect them to controller functions


[Link]("/", [Link]); // GET /students
[Link]("/:id", [Link]); // GET /students/:id

[Link] = router;
📁 controllers/[Link]
// Controller file — contains logic for each route

// Get all students


[Link] = (req, res) => {
const students = [
{ id: 1, name: "Ami" },
{ id: 2, name: "Rahul" }
];
[Link](students);
};

// Get one student by ID


[Link] = (req, res) => {
const id = parseInt([Link]);
const students = [
{ id: 1, name: "Ami" },
{ id: 2, name: "Rahul" }
];

const student = [Link](s => [Link] === id);


if (!student) {
return [Link](404).json({ message: "Student not found" });
}
[Link](student);
};
📁 [Link]
const express = require("express");
const app = express();
const PORT = 3000;

// Import routes
const studentRoutes = require("./routes/studentRoutes");

// Middleware to parse JSON


[Link]([Link]());

// Mount student routes


[Link]("/students", studentRoutes);

// Start the server


[Link](PORT, () => {
[Link](`Server running at [Link]
});
2.3 Middleware and API Basics
2.3.1 Understanding Middleware in Express
Middleware in Express refers to functions that process requests before reaching the route handlers.
These functions can modify the request and response objects, end the request-response cycle, or call
the next middleware function. Middleware functions are executed in the order they are defined.
They can perform tasks like authentication, logging, or error handling. Middleware helps separate
concerns and manage complex routes efficiently.
Middleware working
Syntax
[Link]((req, res, next) => {
[Link]('Middleware executed');
next();
});
 (req, res, next) => {}: This is the middleware function where you can perform actions on the
request and response objects before the final handler is executed.
 next(): This function is called to pass control to the next middleware in the stack if the
current one doesn't end the request-response cycle.
What Middleware Does in [Link]
Middleware functions in [Link] can perform several important tasks:
1. Execute Code: Middleware can run any code when a request is received.
2. Modify Request and Response: Middleware can modify both the request (req) and response
(res) objects.
3. End the Request-Response Cycle: Middleware can send a response to the client, ending the
cycle.
4. Call the Next Middleware: Middleware can call next() to pass control to the next function in
the middleware stack.
How Middleware Works in [Link]?
In [Link], middleware functions are executed sequentially in the order they are added to the
application. Here’s how the typical flow works:
1. Request arrives at the server.
2. Middleware functions are applied to the request, one by one.
3. Each middleware can either:
 Send a response and end the request-response cycle.
 Call next() to pass control to the next middleware.
4. If no middleware ends the cycle, the route handler is reached, and a final response is sent.
Types of Middleware
ExpressJS offers different types of middleware and you should choose the middleware based on
functionality required.
1. Application-level Middleware
Application-level middleware is bound to the entire Express application using [Link]() or
[Link](). It executes for all routes in the application, regardless of the specific path or HTTP
method.
This type of middleware is commonly used for tasks like logging, body parsing, authentication checks,
or setting headers for every incoming request.
[Link]([Link]()); // Parses JSON data for every incoming request
[Link]((req, res, next) => {
[Link]('Request received:', [Link], [Link]);
next();
});
2. Router-level Middleware
Router-level middleware is applied to a specific router instance using [Link]() or
[Link](). It only applies to routes defined within that particular router, making it perfect for
modular applications where middleware is only relevant to specific groups of routes.
This type of middleware is often used to group related routes (e.g., all routes related to
authentication or user management) and apply middleware logic to them.
const router = [Link]();

// Apply middleware to only this router's routes


[Link]((req, res, next) => {
[Link]('Router-specific middleware');
next();
});

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


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

[Link]('/user', router); // The middleware applies only to routes under "/user"


3. Error-handling Middleware
Error-handling middleware is a special type of middleware used to catch and respond to errors
during the request-response cycle. It is defined with four parameters: err, req, res, next.
This middleware is essential for sending a consistent error response and avoiding unhandled
exceptions that might crash the server.
[Link]((err, req, res, next) => {
[Link]([Link]); // Log the error stack
[Link](500).send('Something went wrong!');
});
4. Built-in Middleware
Express provides built-in middleware to help with common tasks, like serving static files or parsing
data.
For example, [Link]() serves files like images, and [Link]() helps parse incoming JSON
data.
[Link]([Link]('public')); // Serves static files from the "public" folder
[Link]([Link]()); // Parses JSON payloads in incoming requests
5. Third-party Middleware
Third-party middleware is developed by external developers and packaged as npm modules. These
middleware packages add additional functionality to your application, such as request logging,
security features, or data validation.
For example, the morgan middleware logs HTTP requests, and body-parser helps parse incoming
request bodies for easier handling of form data.
const morgan = require('morgan');
[Link](morgan('dev')); // Logs HTTP requests using the "dev" format

const bodyParser = require('body-parser');


[Link]([Link]({ extended: true })); // Parses URL-encoded bodies
Steps to Implement Middleware in Express
Step 1: Initialize the [Link] Project
npm init -y
Step 2: Install the required dependencies.
npm install express
Step 3: Set Up the Express Application
// Filename: [Link]
const express = require('express');
const app = express();
const port = [Link] || 3000;

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


[Link]('<div><h2>Welcome to GeeksforGeeks</h2><h5>Tutorial on
Middleware</h5></div>');
});

[Link](port, () => {
[Link](`Listening on port ${port}`);
});
Step 4: Start the Application:
node [Link]
Output:
When you navigate to [Link] you will see:
Welcome to GeeksforGeeksTutorial on Middleware
Middleware Chaining
Middleware can be chained from one to another, Hence creating a chain of functions that are
executed in order. The last function sends the response back to the browser. So, before sending the
response back to the browser the different middleware processes the request.
The next() function in the express is responsible for calling the next middleware function if there is
one.
Modified requests will be available to each middleware via the next function

Middleware chaining example


const express = require('express');
const app = express();

// Middleware 1: Log request method and URL


[Link]((req, res, next) => {
[Link](`${[Link]} request to ${[Link]}`);
next();
});

// Middleware 2: Add a custom header


[Link]((req, res, next) => {
[Link]('X-Custom-Header', 'Middleware Chaining Example');
next();
});

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

[Link](3000, () => {
[Link]('Server is running on port 3000');
});
 Middleware 1: Logs the HTTP method and URL of the incoming request.
 Middleware 2: Sets a custom header X-Custom-Header in the response.
 Route Handler: Sends a "Hello, World!" message as the response.
Output
When a client makes a GET request to [Link] the server responds with:
Hello, World!
Advantages of using Middleware
 Modularity: Breaks down complex tasks into smaller, manageable functions.
 Reusability: Middleware functions can be reused across different routes or applications.
 Maintainability: Organizes code logically, making it easier to manage and update.
 Error Handling: Centralizes error handling, improving the application's robustness.
 Performance Optimization: Allows for tasks like caching, compression, and security checks to
be handled efficiently.

2.3.2 Built-in and Custom Middleware


[Link]()
It helps your app read JSON data that comes from the client. It helps your app understand JSON data
from the body of POST or PUT requests.
 We have .json file
{
"name": "Ami"
}
Then inside your route, you can directly access it using .js file
 [Link] // gives "Ami"
So, it’s like a translator that converts raw JSON text into a JavaScript object for your code.

[Link]('public')
It helps you serve static files (like HTML, CSS, images) directly from a folder.
Example for Built-in Middleware
const express = require("express");
const app = express();
// Built-in middleware
[Link]([Link]()); // Parses JSON body
[Link]([Link]("public")); // Serves static files

// Example POST route to test [Link]()


[Link]("/student", (req, res) => {
[Link]([Link]); // See the JSON data sent by client
[Link]("✅ JSON data received!");
});
[Link](3000, () => [Link]("Server running on [Link]
Folder structure:
project/
├─ [Link]
└─ public/
└─ [Link]
If you open:
👉 [Link]
The browser will show the HTML page — because of [Link]('public').
Custom Middleware
You can make your own middleware function — for example, to check if a user is allowed to access a
route.
Here’s your example, explained simply
function checkAuth(req, res, next) {
if ([Link] === "secret") {
next(); // Continue to the next middleware or route
} else {
[Link](403).send("❌ Access Denied");
}
}

[Link](checkAuth); // Register the custom middleware


here,
Line Explanation
Reads the value of token from the URL (example:
[Link]
?token=secret)
if ([Link] === "secret") Checks if the token matches 'secret'
next() Allows the request to continue to the next step (the route)
[Link](403).send("Access Stops the request and sends an error message if the token is
Denied") wrong

2.3.3 Introduction to CORS and Environment Variables


CORS (Cross-Origin Resource Sharing)

CORS in [Link] is a security mechanism that allows a web server to explicitly permit web
applications from different origins (domains, protocols, or ports) to access its resources. It is
necessary to bypass the browser's default same-origin policy, which blocks such cross-origin
requests for security reasons.

Cross-Origin Resource Sharing (CORS) is a mechanism that allows web applications to access
resources from different domains. In [Link], CORS is commonly used to enable web applications
running on one domain to access resources located on another domain.

1. Install the CORS middleware package

To enable CORS in your [Link] application, you need to install the CORS middleware package. You
can install it using npm by running the following command:

npm install cors


2. Enable CORS in your [Link] application

Once you have installed the CORS middleware package, you can enable CORS in your [Link]
application by requiring the package and calling it as middleware in your application.

const express = require('express');


const cors = require('cors');
const app = express();
[Link](cors());

This will enable CORS for all routes in your application. If you want to enable CORS for a specific
route, you can pass the CORS middleware to that route as shown below.

const express = require('express');


const cors = require('cors');
const app = express();
[Link]('/products', cors(), function (req, res, next) {
[Link]({msg: 'This route has CORS enabled'});
});

Note : When React (frontend) runs on port 3000 and Express (backend) runs on 5000,
the browser blocks requests by default.
CORS allows the two to communicate safely.

🔸 Environment Variables (.env)

Environment variables are used in [Link] to manage configuration settings and sensitive data (like
API keys and passwords) outside of the codebase. In [Link], these variables are accessed via the
global [Link] object.

Setting Environment Variables

How you set environment variables depends on your operating system and environment
(development, production, Docker, etc.).

 Command Line (Temporary for current session):

o Windows (Command Prompt): set PORT=3000 followed by node [Link]

o Windows (PowerShell): $env:PORT=3000; node [Link]

 Using a .env file :


For local development, the most common way is to use a .env file and the popular dotenv
package to load them automatically into [Link] .
 Install the package: npm install dotenv .

 Create a file named .env in your project's root directory:

 # .env file
 PORT=4000
 DB_HOST=localhost
 API_SECRET=your_secret_key
 Load the variables in your application's entry file (e.g., [Link] ):

javascript

require('dotenv').config();
const port = [Link];
// ... rest of your application code

Accessing Environment Variables in [Link]

You can access an environment variable in your [Link] code


using [Link].<VARIABLE_NAME> .

javascript
// Example: Accessing a PORT variable
const port = [Link] || 3000; // Use the environment variable or a default value
[Link](`Server running on [Link]

// Example: Accessing a database host


const dbHost = [Link].DB_HOST;

All values retrieved from [Link] are strings, so you must perform type conversion if you need
numbers or booleans (e.g., parseInt([Link], 10) or [Link].SHOULD_LOG ===
'true' ).

Common questions

Powered by AI

Using both route and query parameters in an Express.js application offers flexibility in how data is accessed and filtered. Route parameters, like ':id' in '/students/:id', are used to access specific resources, making URIs meaningful and clear. Query parameters, on the other hand, allow optional filtering, pagination, or sorting, as seen in '/students?course=MCA'. Combining these parameters enables more dynamic and complex data retrieval, accommodating various user needs without complicating the URI structure .

POST and PUT methods differ significantly in semantics and idempotency, impacting their role in RESTful APIs. POST is not idempotent; it is used to create resources under a collection, meaning repeated identical requests create multiple objects. In contrast, PUT is idempotent; it replaces or updates an existing resource entirely, such that multiple identical requests yield the same resource state. These differences guide their use: POST is preferred for resource creation where uniqueness is expected per request, while PUT is suitable for updates or complete resource replacements where state consistency is critical .

Modular routing, especially with router-level middleware, brings significant advantages to an Express.js application by organizing routes into smaller, manageable groups. It allows middleware to be applied only to relevant routes, enhancing efficiency and readability. This practice reduces redundancy, as shared functionality like authentication can be layered only where needed. It also helps in managing permissions, debugging, and scaling, making large applications more maintainable by encapsulating route-specific logic within routers .

Middleware chaining enhances an Express.js server setup by allowing multiple middleware functions to be executed in sequence. This setup is potent for operations requiring layered processing, such as authentication checks followed by logging. Each middleware function can modify requests or responses, add headers, or perform logging before finally reaching the route handler. Chaining modularizes the server logic, making it easier to debug, update, and maintain. It also optimizes performance by terminating request cycles when appropriate without reaching route handlers .

Middleware in an Express.js application serves as a series of functions that execute during the lifecycle of a request to the server. It can perform tasks like authentication, logging, and error handling, which helps separate concerns and manage complex routes efficiently. Middleware can modify request and response objects, execute code, terminate request cycles, or call the next middleware, impacting the server architecture by allowing for modularity, reusability, and maintainability. Each middleware function is executed sequentially in order, and it can significantly optimize performance by handling tasks such as caching and security checks .

RESTful architecture emphasizes uniform interfaces, statelessness, and resource-orientation, heavily influencing the structuring of URL endpoints. URLs should use nouns for resources (/students, /courses) and maintain consistency in path formatting, such as using plural nouns for collections. Proper nesting should reflect resource hierarchy (/students/42/grades). REST requires endpoints to relate logically to resource manipulations via HTTP methods, ensuring predictability and discoverability in API interactions, which is crucial for clients to self-guide their use of the API .

express.static() and express.json() are considered essential built-in middleware in many Express.js applications because they address common basic needs. express.static() serves static files like HTML, CSS, and images from a specified directory, enabling easy integration of front-end content with the back-end server. express.json() parses incoming requests with JSON payloads, simplifying the process of handling API input data and allowing a standard method to access JSON in routes. Both middleware functions streamline development and help maintain clean and organized application code .

Understanding idempotency and HTTP method semantics is crucial for designing reliable RESTful APIs. Idempotency ensures that certain operations, like GET, PUT, and DELETE, can be called multiple times without different outcomes, which is vital for safe retry logic in client-server communication. This reliability aids in robust client-side caching and server-side consistency handling. GET requests should not alter the server state, while multiple PUT or DELETE requests on the same resource usually yield the same result. This keeps the APIs predictable, a key principle of RESTful design .

Implementing CORS in an Express.js application has significant benefits. CORS allows web applications to access resources from different domains, essential for enabling API interaction in a distributed network environment. It enhances the flexibility and capability of web apps by bypassing the browser’s default same-origin policy strictly enforced for security reasons. However, it presents challenges such as potential security vulnerabilities if misconfigured, as it may unintentionally expose sensitive resources to the public. Careful configuration is required to ensure that only allowable domains have access to resources .

HTTP status codes play a critical role in API responses by indicating the result of a client's request. They improve client-server communication by providing clients with clear, standardized messages about the success or failure of requests. Codes like 200 (OK) signal success, 201 (Created) indicates resource creation, and 404 (Not Found) informs about missing resources. Proper use of status codes helps clients to handle responses correctly, like retrying requests upon receiving 503 (Service Unavailable), thereby enhancing application resilience and efficiency .

You might also like