fbpx

Express.js Framework

Express.js is a web application framework for Node.js that simplifies the process of building robust and scalable web applications. It provides a set of features for developing web and mobile applications, including routing, middleware support, template engines, and more. Express.js is widely used in the Node.js community and is known for its simplicity and flexibility. Here’s an overview of key concepts and features of Express.js:

1. Installation:

  • To use Express.js, first install it in your project using npm. Open a terminal and run the following command in your project directory:
    bash npm install express

2. Hello World with Express:

  • Create a basic Express app with a “Hello World” route. Create a file (e.g., app.js) and use the following code: const express = require('express'); const app = express(); const PORT = 3000; app.get('/', (req, res) => { res.send('Hello, Express!'); }); app.listen(PORT, () => { console.log(`Server running at http://localhost:${PORT}/`); });
  • Run the server:
    bash node app.js
  • Access the server in a web browser at http://localhost:3000/.

3. Routing:

  • Express provides a simple and expressive way to define routes for handling different HTTP methods and URL patterns. Example: app.get('/about', (req, res) => { res.send('About Page'); }); app.post('/contact', (req, res) => { res.send('Contact Form Submitted'); });

4. Middleware:

  • Middleware functions are functions that have access to the request, response, and the next middleware function in the application’s request-response cycle. They can perform tasks, modify request and response objects, and end the request-response cycle. Example: // Middleware function const logger = (req, res, next) => { console.log(`Request received at ${new Date()}`); next(); // Call the next middleware in the chain }; app.use(logger);

5. Template Engines:

  • Express supports template engines for rendering dynamic views. Popular template engines include EJS, Pug (formerly Jade), and Handlebars. Install a template engine using npm and set it up in your Express app: npm install ejs // Set EJS as the template engine app.set('view engine', 'ejs'); // Render a view app.get('/profile/:name', (req, res) => { const data = { name: req.params.name }; res.render('profile', data); });

6. Static Files:

  • Use the express.static middleware to serve static files, such as images, stylesheets, and JavaScript files. Example:
    javascript // Serve static files from the "public" directory app.use(express.static('public'));

7. Middleware Libraries:

  • Express.js has a rich ecosystem of middleware libraries that can be easily integrated into your application. Some commonly used middleware include:
    • body-parser: Parses incoming request bodies in a middleware before your handlers, available under the req.body property.
    • morgan: HTTP request logger middleware.
    • cookie-parser: Parse Cookie header and populate req.cookies.

8. Error Handling:

  • Express provides a way to handle errors using middleware functions with four parameters. Example:
    javascript app.use((err, req, res, next) => { console.error(err.stack); res.status(500).send('Something went wrong!'); });

9. RESTful APIs with Express:

  • Express is commonly used to build RESTful APIs. It supports HTTP methods such as GET, POST, PUT, and DELETE for creating, reading, updating, and deleting resources. Example: // RESTful API for managing a list of items let items = []; app.get('/api/items', (req, res) => { res.json(items); }); app.post('/api/items', (req, res) => { const newItem = req.body; items.push(newItem); res.json(newItem); });

10. Express Generator:

  • Express Generator is a command-line tool that scaffolds out a new Express application with a predefined directory structure. Install it globally using npm:
    bash npm install -g express-generator
    Create a new Express app:
    bash express myapp cd myapp npm install npm start

Express.js is a versatile framework that can be used for a wide range of web applications, from small projects to large-scale enterprise applications. Its simplicity and flexibility make it a popular choice for developers working with Node.js. As you explore Express.js further, you’ll discover additional features and best practices for building modern web applications.