+4 votes
136 views
by (3k points)

Middlewares in Node.js


1 Answer

+5 votes
by (3k points)

middlewares
Controllers

Middleware is a very important concept to develop on Node.js, the platform for use javascript on the server side.

In this tutorial we will learn a very important for those who develop in Node.js, the middleware concept.

A middleware is a block of code that runs between the request makes the user (request) until the request reaches the server.

Middlewares use is inevitable in an application in Node.js, and the most common example is to create a middleware to provide access to a specific URL to a user logged in, so let's see how to do this.

middlewares

Let's pretend that we have created a server and two express routes ( '/', / admin /),

const middlewares =  {

    isLoggedIn :  function  ( req , res , next )  { 
        if  ( req . user )  return  next ( ) ; 
        res . redirect ( '/' ) ; 
    } 
} ; 
module . exports = middlewares ;

This is the most common of whether a user is not logged or middleware. If this log we send the method next () for the driver to continue its execution, if you do not deny access and redirect to another url res.redirect () , at the end we export the variable middleware and we can use it from any other file in your project.

In this same file we can add more middlewares.

const middlewares =  {

    isLoggedIn :  function  ( req , res , next )  { 
        if  ( req . user )  return  next ( ) ; 
        res . redirect ( '/' ) ; 
    } ,
     isSuperUser :  function  ( req , res , next )  { 
        if  ( req . user . is_superuser )  return  next ( ) ; 
        res . redirect ( '/' ) ; 
    } 
} ; 
module . exports = middlewares ;

With this we have two middleware to use, now we will see how we can use these middleware in a route.

Controllers

Before a request reaches a driver passes by middlewares have on the road. How to add a route middleware? Very easy.

const isLoggedIn =  require ( './middlewares' ) . isLoggedIn ;

router . route ( '/ admin /' ) 
    . get ( isLoggedIn ,  function  ( req , res )  { 
     . . . . 
    } ) ;

To add a middleware, just put it in the HTTP method we are using, with that anger first middleware and depending on whether the user is logged in or not, allows access to the controller or send it to another. 

If you want to put a middleware to all routes from a controller we can do this.

router . use ( isLoggedIn ) ;

With this all routes declared within that router will have the active middleware.


statcounter statistics counter
...