0% found this document useful (0 votes)
37 views10 pages

Express Js

Uploaded by

anjanashri108
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)
37 views10 pages

Express Js

Uploaded by

anjanashri108
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/ 10

Express js

1. Express js
2. Environment
3. Routing.
4. HTTP methods .
5. Middleware .
6. Cookies
7. Session
8. Authentication
9. authorisation
10. Restful API’s
11. Error handling
12. Debugging
Express js
Express.js is a lightweight and flexible web application framework for Node.js.
It is simple to learn and use.
Highly customizable due to its modular structure.
Strong community support and extensive documentation.
And used for building robust and scalable web applications and APIs,
simplifying the development process by providing a set of tools and features.

Features:
● Fast and Efficient: Built on Node.js, Express.js ensures high performance
and speed.
● Routing: Supports dynamic routing for handling different URL paths and
HTTP methods.
● Middleware: Allow processing of requests and responses. It supports
built-in middleware for tasks like parsing request bodies and serving static
files.
● Error Handling: Provides a structured mechanism for error detection and
handling.
● Extensibility: Offers a vast library of third-party modules and plugins to
extend functionality.
● REST APIs: Designed for creating RESTful APIs with ease, making it popular
for backend services.
Environment in expressJS
Environment in Express.js:
● The environment in Express.js refers to the mode or setting in which an
application is running, such as development, testing, or production.
● It determines how the application behaves and configures itself, such as
connecting to databases, logging, or enabling debugging.

Environment Variables (EVs):


● Environment Variables are key-value pairs used to configure applications
without hardcoding sensitive or environment-specific data.
● Examples include database credentials, API keys, or server ports.

Purpose of Using EVs in Express.js:


● Security: Keeps sensitive data like passwords and API keys out of the
source code.
● Portability: Allows the application to run seamlessly in different
environments (e.g., local, staging, production).
● Flexibility: Simplifies switching between environments without altering
the codebase.

Common Environment Variables in Express.js:


● NODE_ENV: Specifies the application mode, typically set to development,
testing, or production.
● PORT: Determines the port on which the server runs.
● DATABASE_URL: Specifies the database connection string.
● API_KEY: Stores API credentials for external services.
● DEBUG: Enables or disables debugging logs.
Setting up ENVs:
● Environment variables can be set manually in the terminal, stored in
configuration files like .env, or managed by deployment platforms (e.g.,
Heroku, AWS).
● In Express.js, environment variables are accessed using
process.env.<VARIABLE_NAME>.
● process.env is a global object provided by Node.js to manage
environment-specific configurations.
● Use a .env file for local development to centralize variable
management.
● Keep the .env file out of version control (add it to .gitignore).
● Use a library like dotenv to load environment variables from a .env file
during development.
● Validate environment variables to ensure required ones are set.
● Promotes separation of concerns by decoupling configuration from code.
● Enhances maintainability and scalability of applications.
● Simplifies deployment to different environments.

Routing
Routing in Express.js refers to defining the endpoints (or routes) of an
application and specifying how it should respond to client requests for each
endpoint. It is a fundamental feature for building web applications and
APIs.

Structure of a Route:
● Path (URL): The specific endpoint where the request is directed.
● HTTP Method: Specifies the type of action, such as GET, POST, PUT,
DELETE, etc.
● Callback Function (Handler): Defines how to process the request and
send a response.
Http methods
GET

● Purpose: Retrieve information from the server without changing it.


● Use Case: Fetching resources like user details, lists, or files.
● Effect on Repetition: Repeating the request gives the same result without
side effects.

POST

● Purpose: Send data to the server to create a new resource.


● Use Case: Creating a new user, submitting a form, or adding a new entry.
● Effect on Repetition: Repeating the request creates multiple similar
resources.

PUT

● Purpose: Update or completely replace an existing resource on the


server.
● Use Case: Updating user details or replacing an item in a database.
● Effect on Repetition: Repeating the request produces the same outcome;
the resource is updated the same way.

DELETE

● Purpose: Remove a resource from the server.


● Use Case: Deleting a user account or removing an item.
● Effect on Repetition: Repeating the request has no further impact if the
resource is already deleted
Middlewares
Middleware functions in Express.js are functions that execute during the
lifecycle of a request to the server. Here's a simple explanation:

➔ Definition: Middleware functions process requests before they reach the


final route handler or response.
➔ Types:
◆ Built-in Middleware: Comes with Express (e.g., express.json() for
parsing JSON).
◆ Third-party Middleware: Installed via npm (e.g., cors, body-parser).
◆ Custom Middleware: Created by developers for specific tasks.
➔ Purpose:
◆ Modify the request or response objects.
◆ Execute specific tasks like authentication, logging, or error handling.
◆ Stop the request-response cycle or pass control to the next middleware.
➔ Execution Order: Middleware is executed in the order it's defined in the
code.
➔ Next Function: Each middleware uses the next() function to pass control
to the next middleware or route.
➔ Common Use Cases:
◆ Parsing request bodies (e.g., JSON, form data).
◆ Validating user inputs.
◆ Implementing authentication and authorization.
◆ Logging requests for debugging or analytics.
◆ Handling errors consistently.
Cookies, sessions, authentication &
authorisation
Concepts of Managing user data and controlling access

Cookies
➔ Definition: Small pieces of data stored on the user's browser by the
server.
➔ Purpose:
◆ Track user activity (e.g., remember logged-in users).
◆ Store small amounts of information (e.g., preferences, session IDs).
➔ Key Characteristics:
◆ Persistent (can have an expiration date).
◆ Can be set as secure and HTTP-only for safety.
➔ Use Case: Shopping carts, saving user preferences, and keeping users
logged in.

Sessions
➔ Definition: Server-side storage of user-specific data associated with a
session ID.
➔ Purpose:
◆ Manage user interactions with the server while logged in or browsing.
◆ Store sensitive information securely on the server.
➔ Key Characteristics:
◆ Session IDs are typically stored in cookies.
◆ Data is cleared when the session expires or the user logs out.
➔ Use Case: Tracking logged-in users, maintaining shopping carts across
pages.

Authentication
➔ Definition: The process of verifying the identity of a user.
➔ Purpose: Ensure the user is who they claim to be (login process).
➔ Common Methods:
◆ Username and password.
◆ Tokens (e.g., JWT).
◆ Biometric verification (e.g., fingerprint, face recognition).
➔ Use Case: Logging into a website or mobile app.

Authorization
➔ Definition: The process of determining what actions or resources a user
is allowed to access.
➔ Purpose: Control access based on roles or permissions.
➔ Key Difference from Authentication: Happens after authentication;
confirms what a user can do.
➔ Use Case:
◆ Allowing admins to access sensitive data.
◆ Restricting certain pages to specific users.

Summary of Relationships
● Cookies and Sessions: Cookies often store the session ID to link users to
their data on the server.
● Authentication and Authorization: Authentication verifies who the user
is, while authorization checks what they can access.
Restful APIs
● RESTful APIs are based on REST principles, emphasizing scalability and
simplicity.
● Resources are represented by unique URLs and manipulated using HTTP
methods.
● Common HTTP methods: GET (retrieve), POST (create), PUT (update),
DELETE (remove).
● Responses are often in JSON or XML, making data easy to exchange.
● Stateless: Each request is independent and contains all required
information.
● Designed for flexibility and compatibility across different platforms and
systems.
● Supports CRUD operations for managing resources.
● Widely used in web, mobile, and IoT for seamless system integration.

Error handling
● Purpose: To manage and respond to errors that occur during request
processing.
● Default Error Handling: Express has a built-in error handler that sends a
generic response if an error occurs.
● Custom Error Handling: Developers can define their own error-handling
middleware for specific error responses.
● Error-Handling Middleware: Special middleware with four arguments:
(err, req, res, next).
● Order of Middleware: Error-handling middleware must come after all
other middleware and routes.
● Common Usage: Logging errors, sending custom error messages, or
handling specific types of errors.
● HTTP Status Codes: Used to indicate the type of error (e.g., 404 for not
found, 500 for server error).

Debugging
● Console Logging: Use console.log() to print values and track the flow of
requests and responses.
● Debug Module: Express can integrate with the debug module to enable
more granular logging (e.g., DEBUG=express:* node app.js).
● Error Handling: Implement custom error-handling middleware to catch
and log errors.
● Node.js Inspector: Use node --inspect to launch the app in debugging
mode and connect it to Chrome DevTools for interactive debugging.
● Breakpoints: Use debugger statements in your code to pause execution
and inspect variables.
● Third-Party Tools: Use tools like Postman or Insomnia to test API routes
and inspect responses.
● Logging Libraries: Use advanced logging libraries like winston or morgan
for detailed logs and easier tracking of issues.
● Check Middleware Order: Ensure middleware is applied in the correct
order to catch errors early.

You might also like