Express.js #
Express.js is a popular web application framework for Node.js that simplifies the development of server-side applications and APIs. Here’s a basic overview of the Express framework in Node.js:
Installation: #
Install Express using npm, the Node.js package manager:
npm install express
Hello World Example: #
Create a simple Express app with a “Hello, World!” endpoint:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Access the application by navigating to http://localhost:3000 in your web browser.
Routing: #
Express allows you to define routes for different HTTP methods and URLs:
app.get('/about', (req, res) => {
res.send('About Us');
});
app.post('/api/data', (req, res) => {
// Handle POST request
});
Middleware: #
Middleware functions are functions that have access to the request, response, and the next function in the application’s request-response cycle.
app.use(express.json()); // Parse JSON requests
app.use(express.static('public')); // Serve static files from the 'public' directory
app.use((req, res, next) => {
console.log('Middleware executed');
next(); // Move to the next middleware or route handler
});
Template Engines: #
Express supports template engines like EJS, Pug, and Handlebars for rendering dynamic HTML.
npm install ejs
app.set('view engine', 'ejs');
app.get('/dynamic', (req, res) => {
res.render('dynamic', { name: 'John' });
});
Query Parameters and Route Parameters: #
Access query parameters and route parameters in Express:
app.get('/user', (req, res) => {
const userId = req.query.id;
res.send(`User ID: ${userId}`);
});
app.get('/user/:id', (req, res) => {
const userId = req.params.id;
res.send(`User ID: ${userId}`);
});
Error Handling: #
Use error-handling middleware to catch and handle errors:
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Internal Server Error');
});
Express Router: #
Organize routes into separate files using Express Router:
// routes.js
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
res.send('Router Home');
});
module.exports = router;
// app.js
const routes = require('./routes');
app.use('/router', routes);
Middleware Stack: #
Middleware can be specific to a route or applied globally:
const middleware1 = (req, res, next) => { /* ... */ };
const middleware2 = (req, res, next) => { /* ... */ };
app.get('/route1', middleware1, (req, res) => {
// ...
});
app.get('/route2', [middleware1, middleware2], (req, res) => {
// ...
});
app.use(middleware1); // Applies globally
RESTful APIs: #
Express is commonly used to build RESTful APIs, handling HTTP methods such as GET, POST, PUT, DELETE.
app.get('/api/users', (req, res) => {
// Retrieve list of users
});
app.post('/api/users', (req, res) => {
// Create a new user
});
Express.js provides a flexible and powerful foundation for building web applications and APIs in Node.js. Its simplicity, middleware system, and robust routing capabilities make it a go-to choice for developers when creating scalable and maintainable server-side applications.