Introduction to Express.js

Getting Started with Express.js

Introduction to Express.js

Welcome to Day 9 of our Node.js blog series!😉

Today, we'll introduce Express.js, a popular and powerful web application framework for Node.js. Express.js simplifies the process of building robust, scalable web applications and APIs. We'll cover what Express.js is, how to set up an Express application, basic routing, and the use of middleware. By the end of this post, you'll have a solid foundation for building web applications with Express.js.

What is Express.js?

Express.js, often simply referred to as Express, is a minimal and flexible Node.js web application framework that provides a robust set of features for building web and mobile applications. It facilitates the management of routes, handling HTTP requests and responses, and simplifies middleware integration, making it easier to develop server-side applications.

Key features of Express.js include:

  • Middleware Support: Use middleware functions to handle requests, responses, and application logic.

  • Routing: Define routes to handle different HTTP methods and URL paths.

  • Template Engine Integration: Use template engines like Pug or EJS to render dynamic content.

  • Static File Serving: Serve static files such as images, CSS, and JavaScript easily.

Setting Up an Express.js Application

To get started with Express, you need to install it using npm (Node Package Manager) and set up a basic application.

  1. Installing Express:

    First, initialize a new Node.js project and install Express.

     mkdir my-express-app
     cd my-express-app
     npm init -y
     npm install express
    
  2. Creating a Basic Express Application:

    Create a new file called app.js and set up a basic Express application.

     const express = require('express');
     const app = express();
     const port = 3000;
    
     // Define a simple route
     app.get('/', (req, res) => {
       res.send('Hello, Express!');
     });
    
     // Start the server
     app.listen(port, () => {
       console.log(`Server running at http://localhost:${port}`);
     });
    
    • Explanation:

      • const express = require('express');: Imports the Express module.

      • const app = express();: Creates an Express application.

      • app.get('/', (req, res) => {...});: Defines a route for the root URL (/) that sends a "Hello, Express!" response.

      • app.listen(port, () => {...});: Starts the server on port 3000 and logs a message when the server is running.

  3. Running the Application:

    Start the Express application by running the following command:

     node app.js
    

    You should see the message "Server running at localhost:3000" in your terminal. You can open a browser and navigate to http://localhost:3000 to see the "Hello, Express!" message.

Basic Routing with Express.js

Routing is a mechanism that maps HTTP requests to specific handlers based on the URL and HTTP method. In Express, you can define routes using methods like get, post, put, and delete.

  1. Defining Routes:

    Define routes to handle different HTTP methods and paths.

     // GET request to the root URL
     app.get('/', (req, res) => {
       res.send('Welcome to the Home Page!');
     });
    
     // GET request to the /about URL
     app.get('/about', (req, res) => {
       res.send('About Us');
     });
    
     // POST request to the /submit URL
     app.post('/submit', (req, res) => {
       res.send('Form Submitted!');
     });
    
     // PUT request to the /update URL
     app.put('/update', (req, res) => {
       res.send('Update Complete!');
     });
    
     // DELETE request to the /delete URL
     app.delete('/delete', (req, res) => {
       res.send('Resource Deleted!');
     });
    
    • Explanation:

      • app.get('/about', (req, res) => {...});: Handles GET requests to the /about URL.

      • app.post('/submit', (req, res) => {...});: Handles POST requests to the /submit URL.

      • app.put('/update', (req, res) => {...});: Handles PUT requests to the /update URL.

      • app.delete('/delete', (req, res) => {...});: Handles DELETE requests to the /delete URL.

  2. Route Parameters:

    You can capture values from the URL using route parameters.

     app.get('/users/:id', (req, res) => {
       const userId = req.params.id;
       res.send(`User ID: ${userId}`);
     });
    
    • Explanation:

      • The :id in the route path is a placeholder for a route parameter. You can access it via req.params.id.
  3. Query Parameters:

    Access query string parameters using req.query.

     app.get('/search', (req, res) => {
       const query = req.query.q;
       res.send(`Search Query: ${query}`);
     });
    
    • Explanation:

      • If you navigate to http://localhost:3000/search?q=Node, the response will be "Search Query: Node".

Middleware in Express.js

Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. Middleware can execute code, modify the request and response objects, end the request-response cycle, and call the next middleware function.

  1. Application-Level Middleware:

    Application-level middleware is bound to an instance of the Express app object using app.use().

     // Logger middleware
     app.use((req, res, next) => {
       console.log(`${req.method} request for '${req.url}'`);
       next(); // Call the next middleware function
     });
    
     // Another middleware example
     app.use((req, res, next) => {
       req.customProperty = 'Custom Value';
       next();
     });
    
     app.get('/', (req, res) => {
       res.send(`Custom Property: ${req.customProperty}`);
     });
    
    • Explanation:

      • The first middleware logs the HTTP method and URL for each request.

      • The second middleware adds a custom property to the request object.

  2. Router-Level Middleware:

    Router-level middleware works similarly to application-level middleware, but it is bound to an instance of express.Router().

     const express = require('express');
     const app = express();
     const router = express.Router();
    
     router.use((req, res, next) => {
       console.log('Router-level middleware');
       next();
     });
    
     router.get('/profile', (req, res) => {
       res.send('User Profile');
     });
    
     app.use('/user', router);
    
     app.listen(3000, () => {
       console.log('Server running on http://localhost:3000');
     });
    
    • Explanation:

      • The middleware logs a message for any request to the /user route.

      • The /user/profile route is handled by the router.

  3. Error-Handling Middleware:

    Error-handling middleware is defined after all other middleware and routes. It takes four arguments: err, req, res, and next.

     app.use((err, req, res, next) => {
       console.error(err.stack);
       res.status(500).send('Something broke!');
     });
    
    • Explanation:

      • This middleware catches any errors that occur during request processing and sends a 500 status code with an error message.
  4. Built-in Middleware:

    Express provides built-in middleware for common tasks, such as serving static files and parsing JSON.

    • Serving Static Files:

        app.use(express.static('public'));
      
    • Parsing JSON:

        app.use(express.json());
      

Conclusion

Today, we've covered the fundamentals of working with Express.js. We explored what Express.js is, how to set up an Express application, define basic routing, and use middleware. Understanding these concepts is crucial for building efficient, maintainable, and scalable web applications with Node.js.

In the next post, we'll delve into Building RESTful APIs with Express.js .Stay tuned for more in-depth Node.js content!