Express.js is a lightweight, unopinionated Node.js framework for building robust and scalable web applications. It provides a wide range of features out of the box, including routing, middleware, request handling, and template rendering, simplifying the development process and enabling rapid application development.
Key Features
- Routing: Express.js allows you to define routes for your application and handle incoming HTTP requests based on various criteria such as URL, HTTP method, and request parameters.
- Middleware: Middleware functions allow you to perform tasks before or after request handling, providing functionality like authentication, authorization, and request logging.
- Request Handling: Express.js offers a comprehensive set of request processing methods that handle the incoming request data, parse it, and respond with appropriate HTTP responses.
- Template Rendering: Express.js supports a variety of template engines, such as EJS, Pug, and Handlebars, enabling you to generate dynamic HTML pages based on data.
- Error Handling: Express.js provides built-in error handling capabilities, allowing you to handle exceptions and return appropriate HTTP error responses.
- Built-in Middleware: Express.js comes with a range of built-in middleware, such as body-parser, cookie-parser, and helmet, which handle common tasks like parsing request bodies and setting security headers.
- Community Support: Express.js has a large and active community, providing a vast ecosystem of plugins, extensions, and resources.
Getting Started
To get started with Express.js, you need to install it using npm or yarn:
npm install express
yarn add express
Create a new Node.js project and create a file named app.js. Start by importing the Express.js library:
const express = require('express');
Routing
Basic Routing
To define a simple route, use the get() method:
const app = express();
app.get('/', (req, res) => {
res.send('Hello, Express!');
});
This route handles GET requests to the root URL (/) and responds with the string "Hello, Express!".
Parameterized Routes
You can use parameters in your routes to capture values from the URL:
app.get('/users/:id', (req, res) => {
res.send(`User ID: ${req.params.id}`);
});
This route matches requests to /users/<some_id> and captures the id value in the req.params object.
HTTP Methods
Express.js supports all HTTP methods:
app.get('/users'); // GET requests
app.post('/users'); // POST requests
app.put('/users/:id'); // PUT requests
app.delete('/users/:id'); // DELETE requests
Middleware
Built-in Middleware
Express.js provides several built-in middleware functions:
const bodyParser = require('body-parser');
app.use(bodyParser.json()); // Parse JSON bodies
const helmet = require('helmet');
app.use(helmet()); // Set security headers
Note: If you get errors indicating that you do not have certain packages , please do install them using "npm install packagename".
Custom Middleware
You can create custom middleware functions:
const authMiddleware = (req, res, next) => {
// Authorization check logic
if (authorized) {
next();
} else {
res.sendStatus(401);
}
};
app.use('/admin', authMiddleware); // Apply middleware to specific paths
Note: Depending on your authentication setup you might compare hashed password from database / verify jwt tokens validitiy / validate oauths.
Request Handling
Request Data
Access request data using the req object:
req.body; // Request body (JSON or form-data)
req.params; // URL parameters
req.query; // Query string parameters
req.headers; // Request headers
req.method; // Request method (e.g., GET, POST)
Response Handling
Send responses using the res object:
res.send('Hello, Express!'); // Send a string
res.json({ user: 'John Doe' }); // Send JSON
res.redirect('/home'); // Redirect to a different route
res.status(404).send('Not Found'); // Set HTTP status code
Template Rendering
To render HTML templates, you can use template engines like EJS:
const ejs = require('ejs');
app.set('view engine', 'ejs'); // Set the default template engine
app.get('/users', (req, res) => {
const users = ['John', 'Jane', 'Peter'];
res.render('users', { users: users }); // Render the 'users' template
});
Error Handling
Express.js provides error handling middleware:
app.use((err, req, res, next) => {
console.log(err);
res.sendStatus(500);
});
This middleware will catch any unhandled errors and respond with HTTP 500 (Internal Server Error).
Deployment
To deploy an Express.js application, you can use a service like Heroku or AWS Elastic Beanstalk, which provides hosting and scaling capabilities.
Code Examples
CRUD Operations
// GET all users
app.get('/users', async (req, res) => {
const users = await User.findAll();
res.json(users);
});
// POST a new user
app.post('/users', async (req, res) => {
const newUser = await User.create(req.body);
res.json(newUser);
});
// GET a specific user
app.get('/users/:id', async (req, res) => {
const user = await User.findByPk(req.params.id);
res.json(user);
});
// PUT (update) a specific user
app.put('/users/:id', async (req, res) => {
const updatedUser = await User.update(req.body, {
where: { id: req.params.id },
});
res.json(updatedUser);
});
// DELETE a specific user
app.delete('/users/:id', async (req, res) => {
const user = await User.findByPk(req.params.id);
user.destroy();
res.sendStatus(200);
});
Authentication and Authorization
// Define the authentication middleware
const authMiddleware = async (req, res, next) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) {
res.sendStatus(401);
return;
}
try {
const decoded = jwt.verify(token, 'my-secret');
req.user = await User.findByPk(decoded.id);
} catch (err) {
res.sendStatus(401);
}
next();
};
// Apply the authentication middleware to protected routes
app.get('/protected', authMiddleware, async (req, res) => {
res.send('This is a protected route');
});
Conclusion
Express.js is a versatile and powerful framework that provides a solid foundation for building robust and scalable web applications. Its flexible routing, middleware capabilities, and support for templating and error handling make it an excellent choice for developers of all skill levels. By leveraging the features and techniques described in this comprehensive guide, you can harness the full potential of Express.js to create efficient, high-performing web applications.
Comments
Post a Comment
Oof!