Express - Js Mastery - Comprehensive Study Notes For Building Powerful Web Applications - by Marazzo - Medium
Express - Js Mastery - Comprehensive Study Notes For Building Powerful Web Applications - by Marazzo - Medium
Search Write
To become proficient in Express.js, here are the main topics you should
focus on learning:
Routing:
In Express, you can define routes to handle different HTTP methods and
URL patterns using the `app.METHOD(path, handler)` functions, where
`METHOD` is the HTTP method (e.g., `get`, `post`, `put`, `delete`) and
`path` is the URL pattern to match. The `handler` function is executed when
a request matching the specified method and path is received.
In this example:
- The `app.get(‘/’, …)` defines a route for handling a GET request to the root
URL (“/”). It sends the response “Hello, World!”.
- The `app.post(‘/users’, …)` defines a route for handling a POST request to
“/users”. It handles the creation of a new user and sends the response “User
created successfully”.
By defining routes using different HTTP methods and URL patterns, you can
handle various types of requests and extract data from the incoming
requests using route parameters (`req.params`) and query parameters
(`req.query`).
Middleware:
Middleware functions in Express are functions that have access to the
request (`req`) and response (`res`) objects and can modify them or perform
additional actions before passing control to the next middleware function in
the chain. Middleware functions are a powerful mechanism for extending
the functionality of your Express application.
Express provides several built-in middleware functions that can be easily
incorporated into your application. Here are some commonly used built-in
middleware functions:
Apart from the built-in middleware functions, you can also create custom
middleware to meet your application’s specific requirements. Custom
middleware functions can be used to add authentication, authorisation,
request validation, logging, or any other custom logic.
In this example:
- The `express.json()` middleware is used to parse JSON request bodies.
- The `app.post(‘/users’, …)` route handles the POST request to `/users` and
extracts the `name` and `email` properties from `req.body`.
- After processing the data, a JSON response is sent with the status code `201`
and a response body containing a success message and the user details.
Error Handling:
Handling errors in Express applications involves catching and handling
errors that occur during the request-response cycle, creating custom error
handling middleware, and sending appropriate error responses to clients.
Here’s an overview of the techniques you can use:
1. Catching Errors: You can catch errors within route handlers using `try-
catch` blocks or by using `async`/`await` with `try-catch` blocks. This allows
you to handle errors within a specific route.
By using these techniques, you can effectively handle errors that occur
within your Express application. Catching errors within route handlers,
creating custom error handling middleware, and sending appropriate error
responses allow you to gracefully handle errors and provide meaningful
feedback to clients when something goes wrong.
Database Integration:
To connect and interact with databases in your Express application, you can
use popular libraries like Mongoose for MongoDB. Mongoose provides a
simple and elegant way to handle data persistence and perform CRUD
(Create, Read, Update, Delete) operations. Here’s an overview of using
Mongoose in your Express application:
In this example, we define a `User` schema with fields `name`, `email`, and
`age`.
These examples show how to create, find, update, and delete users using
Mongoose methods.
// Authentication middleware
function authenticate(req, res, next) {
const token = req.headers.authorization?.split(' ')[1];
if (!token) {
return res.status(401).json({ message: 'Authentication failed' });
}
try {
const decoded = jwt.verify(token, 'secret-key');
req.userId = decoded.userId;
next();
} catch (error) {
return res.status(401).json({ message: 'Invalid token' });
}
}
// Authorisation middleware
function authorise(role) {
return (req, res, next) => {
const userRole = getUserRole(req.userId);
if (userRole !== role) {
return res.status(403).json({ message: 'Access denied' });
}
next();
};
}
// Protected route with authentication and authorisation
app.get('/admin/dashboard', authenticate, authorise('admin'), (req, res) => {
res.json({ message: 'Welcome to the admin dashboard' });
});
1. `next()`: Calling `next()` without any arguments passes the control to the
next middleware function in the chain. It proceeds to execute the next
middleware function or the route handler for the current request.
It’s important to note that if the `next` function is not called within a
middleware function, the request will hang indefinitely, and the client will
not receive a response. Therefore, it’s crucial to ensure that `next` is called
appropriately in each middleware function to maintain the flow of the
request-response cycle.
What kind of…. Express functions do we have available to us?
Express comes with several built-in functions and methods that facilitate the
development of web applications. Here are some commonly used functions
in Express:
5. `app.get()` and `app.set()`: These methods are used to retrieve and set
application-level settings, respectively. They can be used to access and
modify the values set using `app.set()`.
10. `res.render()`: This method is used to render and send a response using a
specified template engine. It is commonly used to render dynamic HTML
views by passing data to the view template.
These are just a few of the functions provided by Express. Express is highly
extensible, and you can also use additional middleware functions and third-
party libraries to enhance the functionality of your application.
Expressjs