Using resuable code in NodeJS

Writing web requests to and from Node server is the heart of sending HTTP requests, but writing repetitive code in our codebase make huge code smell and confusion.

Writing middleware is the common way to refactor and make our code cleaner. What I am about to show in this blog is writing a simple form that utilize a middleware to post the data to Express.

We have created a bodyParser function manually to parse data coming from the form and convert it to an object that looks like this:

{ email: 'example@gmail.com', password: 'asdf', passwordConfirmation: 'asdf' }

What we can do make our code cleaner is to completely delete the bodyParser function that we have created and import a outside middleware by requiring it this way:

What we did instead was to require ‘body-parser’ that ships with express to use and remove the bodyParser that we created. We don’t even need to pass the middleware as a second argument inside the POST request since any function with that route can have access to this middleware.

Using middleware is a very common method to make code cleaner and easier to debug.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
pouya javadi

Building solutions, solving problems, engaging with others are pillars of learning in life.