02Geek HTML5 and JavaScript, TypeScript, React, Flash, ActionScript online School
Previous VideoNext 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.

Video Transcript

00:01In the process of creating our form in the last few
00:04lectures, we reached a pivot point where we need more help.
00:07We can't continue building without the help
00:09of third party integrations.
00:12Now, express JS uses the word middleware
00:15whenever we're adding layers in between our server
00:19or our framework to the server and our actions.
00:21And really what it is, it's kind of like a filter
00:24that changes content, changes something, does some sort
00:27of operation before it lets us continue
00:29doing whatever we were doing.
00:31So a middleware is really a place
00:33where we're adding functionality
00:34or capabilities to our server, enhancing it
00:38to enable us to work.
00:40Now, specifically in our case,
00:42when our form is returning its values,
00:44we're getting back information that's really hard to process
00:47or we're not even trying to, instead of that,
00:49we're approaching a third party tool that is going to
00:52massage that TA data, prepare that data for us,
00:55and then send it to us.
00:57We're gonna integrate that.
00:58So we'll have ga, we'll gain access to the information
01:01that is being sent from the server,
01:03and by that we'll be able to complete the creation
01:06of our form.
01:07So let's jump right into it.
01:09And let's see that philosophy
01:10and action of, again, that idea
01:12that we were talking previously, that especially just
01:15explicitly wants to be dumb.
01:16It doesn't wanna assume how you're gonna
01:18be working with your data.
01:19So it says, Hey, work with a third party tool.
01:21You could choose from many, many tools.
01:24Which one with which, which middleware do you want to use
01:27to be able to manipulate the data data
01:29to the way you want to use it?
01:31So in this lecture, we're gonna pick a middleware,
01:33we're gonna pick a, a package, use its module, integrate it
01:37as a middleware into express js,
01:39and then get the operations that we wanted working.
01:42So let's jump right into it. Let's see it in action.
01:44It'll make a lot more sense
01:45when you're actually looking at it.
01:46So let's jump right into it.
01:49As we were speaking previously about, one of the
01:51interesting factors about express JS is
01:54that it's unopinionated.
01:55Just like no JS is unopinionated,
01:58which means it's not trying to enforce on you
02:01specific developer development styles or ways.
02:05It wants to give you the flexibility to pick your own way
02:09to work if it's to add a framework,
02:10if it's to work on your own.
02:12Now with that in mind, in earlier versions of express js,
02:16we could have just natively accessed the post information.
02:19The problem with that is that it's a very opinionated
02:23concept because this opinion says that I'm gonna know
02:26what are all the types of information that are being said
02:28and I'm gonna be ready for them in advance.
02:31Now instead of that, the approach in in express js,
02:35the current express JS build, is for you to explicitly say,
02:39what is the middleware?
02:40What is the tool that you want to use
02:42that is gonna process requests?
02:44So let's go ahead and do that.
02:45So I'm gonna go into terminal
02:46and I'm just gonna stop my website
02:49by typing on the control C.
02:51And once I've stopped it, I want to go ahead
02:53and I'm going to Oopsie.
02:55I'm gonna go ahead and what I really want to do is I want
02:57to go ahead and install a parser.
02:59Now there's a parser that's called body parser.
03:03And by the way, this is a middleware as we're calling
03:05'cause it's, it's something that's intervening in the
03:07process and extending the features of express js.
03:11So what we're doing here is we're adding a processor
03:13for the body itself.
03:15And I'm gonna go ahead and save this into our package js.
03:19So I'm gonna go ahead and download it.
03:20The package is gonna be downloaded
03:22and ready to be consumed once the package
03:26completes downloading, and I'm gonna go ready into my
03:28editor, I'm gonna go into the editor
03:30and in the editor itself, what I wanna do,
03:32I'm gonna go right all the way on the top here,
03:33and I'm gonna define a new constant.
03:36And this constant, I'm just gonna call it body parser.
03:42And I'm gonna go ahead and I'm gonna ask for
03:45that body parser using the require
03:52Body parser is actually typed with a comma here parser.
03:57So I'm gonna get that body parer.
03:58Once I have the body parser, what I wanna do is I want
04:01to go ahead and add into my application
04:04and tell you, Hey, I want you to use this middleware, I want
04:07to use this new feature.
04:09Now I'm gonna go and I'm gonna ask from the body parer
04:12what functionalities do I want to add?
04:14And the body parer has a few functionalities
04:16and I encourage you to go into the documentation
04:18that it's not very long, which is added
04:20to this chapter, and see the different types.
04:22For example, if we wanted to have JSO interactions,
04:25then I would put your JSO in my case,
04:28I know I have an HTML form, so I don't really want to use,
04:32by the way, I could use a few times.
04:33So I could add a few different uses.
04:35In this case, I want to add a URL ENC coded value in
04:40URL ENC coded and I'm just gonna open
04:43and close a, uh, round bracket.
04:46Now that's all I had to do to enable URL in coded bodies.
04:50Now there are parameters
04:52that you could add into this method.
04:54And again, look into the documentation such some such things
04:57as getting the value in A-U-U-R-L encoded, which means that,
05:01uh, it, it, it, is it gonna parse the URL encoded values.
05:04If there's a space, will it come back with a space
05:06or is it gonna come with URL encoded values,
05:09which don't have that space?
05:10But by default we're gonna get it in, in the encoding
05:13that we really want in our case.
05:14And there's a few other features that you could add.
05:17Once we've used it
05:18and we've added in, all we have to do is go into our, um,
05:21basically to go into our body parer, to basically
05:25to go into any post and go to our request.
05:27And the requests are gonna have a body automatically,
05:30a body object, and I could approach the different variables.
05:33And in this case, that variable is gonna be the name,
05:36which is the only parameter that we're sending in.
05:39So I'm gonna go ahead here and I'm just gonna put your comma
05:43and let's go ahead and even put here a dot.
05:46And I'm gonna go ahead and save this.
05:48Now let's go ahead and run it.
05:50So I'm gonna go into my terminal and I'm just gonna go ahead
05:53and run our server.
05:55By the way, notice that we're getting here.
05:56A small error telling us
05:57that body parer has been deprecated.
06:00It hasn't been deprecated,
06:02but it's originally, like we're talking about,
06:04doesn't exist natively.
06:06So it's not literally deprecated,
06:08although you're better off to find a processor
06:11that you're happy with that is continued in development
06:14while this, this processor has been created
06:17by Express JS itself, which maybe means
06:19that they're not gonna continue on featuring it
06:22or supporting it, although one thing that I've noticed
06:24that if we go ahead
06:25and go into our processor when we put this in here,
06:29and I'm gonna type your extent, extent and say true.
06:34Now what this does is it also enables us to send information
06:37that's not directly only strings.
06:39It enables us to send objects and arrays
06:41and things of that nature within the our forms as well.
06:45That's what the extended feature does.
06:46And by sending it to extended,
06:48we won't get that error anymore.
06:50Although this error doesn't really mean much
06:52because it works just as just fine even if you don't do it.
06:56With that said, let's go and test this out.
06:58If you go into the form itself,
06:59I'm gonna just type here my name.
07:01So I'm gonna say here, Ben, and I'm gonna post it
07:03and we'll see Ben, this is the result.
07:05So there you go. Now you see the full flow
07:07of OTO sending data, receiving data,
07:10and then you can take this data
07:11and manipulate it to the needs of your site.
07:16In this lecture, we were introduced to the concept
07:18of Middlewares, and we've seen it in action,
07:20how it solved our problem with our data.
07:23In the next lecture, we're gonna take it a level deeper from
07:26just using middlewares to actually creating a middleware.

Ready to Level Up Your Skills?

Join thousands of learners on 02GEEK and start your journey to becoming a coding expert today!

Enroll Now for Free!