02Geek HTML5 and JavaScript, TypeScript, React, Flash, ActionScript online School
Previous VideoPrevious Video

Using Middleware in Express.js

Using Middleware in Express.js

In this tutorial, we'll explore how to use middleware in an Express.js application. Middleware is a crucial concept that helps us enhance server functionality by allowing third-party integrations and additional operations before sending the response to the user. In earlier versions of Express.js, we could access post data directly, but with newer versions, the use of middleware is now required.

What is Middleware?

Middleware in Express.js is used as a filter to modify requests and responses before they are processed by the server or sent back to the client. It's like adding layers to the server's capability, and it enhances the server by adding different features or filters at different stages. Middleware can be used for operations such as parsing request bodies, adding headers, logging, and more.

In this tutorial, we will install and use the body-parser middleware to process data sent by the user through forms.

Step-by-Step Implementation

  1. Install Body-Parser Middleware

    The first step is to install body-parser, a popular middleware used to parse incoming request bodies.

    npm install body-parser --save
    

    The --save flag ensures that body-parser is added to your package.json dependencies.

  2. Add Body-Parser to Your Express App

    Once you have body-parser installed, you need to import it into your project and tell Express to use it.

    Open your server file (e.g., index.js) and add the following:

    const bodyParser = require('body-parser');
    
    // Add middleware to parse urlencoded form data
    app.use(bodyParser.urlencoded({ extended: true }));
    

    In this example, we use the urlencoded method to handle incoming form data, allowing us to parse URLs encoded in the form of key-value pairs.

  3. Extended Option

    The { extended: true } option allows you to use rich data, such as nested objects. By setting this to true, we can send more complex data like arrays and objects in our requests.

  4. Update Your Form Handling Code

    Next, update your existing route that handles form submissions to use the parsed form data. Suppose we have a form submission with a field called name, we could access it like this:

    app.post('/submit-form', (req, res) => {
      const name = req.body.name;
      res.send(`Hello, ${name}`);
    });
    

    In this code, we use req.body to access the form data submitted to our server, thanks to body-parser.

  5. Restart and Test

    After making these changes, stop your server if it's currently running and restart it to apply the changes. Run the following command in your terminal to start the server again:

    node index.js
    

    Then, visit the form page and test submitting it. You should see the data successfully parsed and displayed as intended.

Deprecated Warning for Body-Parser

You may notice a warning about body-parser being deprecated. The core functionality of body-parser has been integrated directly into Express as of version 4.16.0. You can use Express's built-in body-parsing middleware instead of the separate body-parser package.

To use the built-in parser, replace:

const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));

With:

app.use(express.urlencoded({ extended: true }));

This simplifies your setup, and you won't need to install body-parser as an external dependency.

Summary

In this tutorial, we've learned about middleware in Express.js, specifically focusing on using the body-parser middleware to process form data. Middleware extends the capabilities of your Express app and enables more efficient handling of different aspects of your requests and responses.

In the next part, we will take it a step further by learning how to create our own middleware to add custom functionalities to our Express server.

Starting up an Express.js server

Learn how to start up an Express.js server, including installation, basic setup, and creating a Hello World server.

08:08

Enabling static files

Learn how to enable static files in Express.js to serve HTML, CSS, JavaScript, and other assets in your web application.

04:47

Routing with Express

In this video, explore the basics of routing in Express.js and how to create dynamic content. Learn about GET, POST, PUT, DELETE, and how to handle different routes effectively.

09:08

Routing with Forms and Static Files in Express.js

Learn how to create dynamic routes with forms and static files using Express.js. This is essential for building interactive web applications.

06:14

Using Middleware in Express.js

Learn how to integrate third-party middleware in Express.js, specifically using body-parser, to handle form data and extend server functionality.

07:29

Creating a middleware in ExpressJS

Learn how to create your own middleware in ExpressJS to handle custom server-side logic and responses.

03:54

Using Express Generator

Learn how to quickly scaffold Express.js applications using the Express Generator tool. This tool helps automate server setup and structure, making development faster and easier.

04:34

Back to React

Learn about integrating Webpack and Babel with React to streamline full stack development.

18:16