Deborah Emeni's Blog

Deborah Emeni's Blog

An Introduction to routes and implementation of middlewares in Nodejs

An Introduction to routes and implementation of middlewares in Nodejs

Before I begin, here are the simple steps to create a nodejs application:

  • Create a folder for your nodejs app.
  • Navigate into that folder in your terminal withcd followed by the name of the folder you just created.
  • Then run npm init -y to generate an empty npm project without going through an interactive process. Once you run that command, the package.json file will be added to your project.
  • Next, install express with this command npm install --save express, this will install express framework as a dependency in your project folder which can be located in the package.json file alongside the node modules folder and package-lock.json file

project folder main vs code.png To check this out, open your project folder in your code editor. (I am using Visual Studio code editor). A short and faster way to do this, is to type code . in your terminal while in your project's directory and now boom! you have your code editor opened with your project. project folder express dependency.png Now moving unto configuring the server to run on a port:

  • Create a file called app.js in your project directory, in it type the following code

project folder app.js .png In the app.js file, you are using the require() function to include express module into your app. As the module express() is a function, you call the function by the const app = express() statement and this creates a new express application for you. The last statement module.exports = app exports the app to be used in other modules in your application.

  • create another file called server.js in your project directory and type the following code in it

project folder server.js .png In this server.js file, line 1 means you are importing the http module to be used in your app to create the server. In line 2, you are setting the environment variable PORT to tell the web server what port to listen to. So, const port = process.env.port || 3000 means whatever is in the variable PORT should be used or 3000 if there is nothing there. In line 3, you are including the app module you created in your server.js file. In line 5 and line 6, you are using the http.createServer() method to create an HTTP Server object that listens to the port and executes the app function each time a request is made. To see if the server is running, in your package.json file add the following code to the scripts section:

    "devStart": "nodemon server.js",
    "start": "node app"

project folder scripts.png To run the script, open your terminal in your project directory and run this command: npm run devStart

project folder devStart.png

Now that you have set up the server running, you can move unto creating routes.

WHAT ARE ROUTES?

A route is a part of express that has access to the HTTP verb(GET, POST, PUT, DELETE, PATCH etc.) and takes two parameters, one of which is a url/path and the second parameter is a callback function.

The first parameter, the url/path is the pattern for the requests. So, any request made with that pattern will be handled by the callback function. The callback function could also be referred to as the route handler. However you want the request to that path/url handled, it will be specified in the code within the callback function. For example;

route.get('/prices', (req, res) => {
//the code that handles the requests made to that url
}

WHY ARE ROUTES CREATED?

For instance, you have a nodejs application you want to build, it could be a book store application. For the book store application, you may need a number of directories that will handle requests and render different data to the user. For example, you may need a directory called store, that includes requests for getting all books or a particular book by an ID and you may need another directory called orders, that gets your orders and creates your orders. To implement this, you have to use HTTP verbs(GET, POST, DELETE etc.) for each of these two directories in your project and a specific path/url must be defined for a user to make requests to and be able to view the response, which in this case will be the books the user ordered.

Now you have to create routes that will specify or define the urls/paths for each of these directories.

HOW TO CREATE ROUTES WITH CODE EXAMPLES

In your code editor, create a folder called api, in the api directory, create another folder called routes. Then in the routes folder, create a file called stores.js and in the same directory within the routes folder, create another file called orders.js.

In the stores.js file, you are going to create routes that are specific to the file using express and a class of express called express.Router. The express.Router class handles the routes

const express = require('express');
const router = express.Router();

Next, export the router to enable it to be used in other modules with

module.exports = router;

In the stores.js route, you want to be able to handle incoming GET requests and POST requests using the express.Router class. You are not working with the database yet so just send a JSON object to the client.

project folder stores.js edited.png You want any requests made to this url '/stores' to be handled by the router handlers functions in your code. To do this, you import the store.js file into the app.js file as a middleware with the require() method

const storesRoute = require('./api/routes/stores');

Then use app.use() to handle the storesRoute middleware. The app.use() function takes two parameters, the path and the callback function. It is used to execute the middleware function at the path specified. So in your app type this in your code editor

app.use('/stores', storesRoute);

So, this has defined a pattern, every time a request is made to a url that starts with '/stores', it will be handled by the storesRoute handler.

Next, for the orders.js file, you want to be able to create orders and delete orders. In your orders.js file, type the following code in your editor

project folder for orders.js route.png Then import the orders.js file to your app.js and set the app.use() to the url, './orders', and the middleware, ordersRoute

project folder for orders.js in app.js.png Now we are done with the routes, to test these end points, start the server with npm run devStart, ensure your server is running. Then use postman to test your API. On postman, in POST, send this request for orders http://localhost:3000/orders

project folder for post request for orders.png and try the other POST request for a particular ID for orders http://localhost:3000/orders/same project folder for post id orders.png Then for the stores route, send this request for GET request http://localhost:3000/stores

project folder get for stores.png and send this POST request for a particular ID(book) http://localhost:3000/stores/bookID

project folder for post id for stores.png

WHAT MIDDLEWARES ARE IN EXPRESS

Middleware is how express handles a sequence of functions, its like a series of functions that you can call. They consist of functions that are called every time a request is made to the server and they are executed with app.use() as we saw above.

WHY MIDDLEWARES ARE IMPORTANT

For instance, you are building an express application that has a module with more than one functions defined. You want these functions to be executed in sequence every time a request is made. So middlewares create this sequence and allows your functions to run one after the other in the order you set.

HOW TO CREATE AND USE MIDDLEWARES WITH CODE SAMPLES IN EXPRESS

In your code editor, create a file/module called middle.js and define these two functions in that file. project folder before final.png The next middleware function is called if the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.

Next, import the functions in your app.js file

const  { prices, items } = require("./middle");

Then use the app.get() request to set the sequence you want the functions to be executed, here we are executing prices at the start of the request, followed by items and every time it completes the request, it sends the JSON object as a response.

app.get('/', items, prices, (req, res) => {
    res.send({ data: "result" });
});

project folder middlewares .png To test this code, run your server with npm run devStart and then make a curl request

project folder final.png

 
Share this