Middlewares in Node.JS

An Express application is essentially a series of middleware function calls.

Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle.

Source : https://expressjs.com/en/guide/using-middleware.html

Types of middleware functions:

  • Application – level middleware
  • Router – level middleware
  • Error – handling middleware
  • Built -in middleware

Application-level middleware to an instance of the app object by using the app.use() and app.METHOD() functions.

var app = express()

app.use(function (req, res, next) {
  console.log('Time:', Date.now())

Router-level middleware works in the same way as application-level middleware, except it is bound to an instance of express.Router().

var router = express.Router()

Load router-level middleware by using the router.use() and router.METHOD() functions.

Error-handling middleware functions in the same way as other middleware functions, except with four arguments instead of three, specifically with the signature (err, req, res, next)):

app.use(function (err, req, res, next) {
  res.status(500).send('Something broke!')

built-in middleware : The only built-in middleware function in Express is express.static. This function is based on serve-static, and is responsible for serving static assets such as HTML files, images, and so on.

The function signature is:

express.static(root, [options])

Difference Between app.use() and router.use() in Express

Source : http://stackoverflow.com/questions/27227650/difference-between-app-use-and-router-use-in-express

router.use(); mounts middleware for the routes served by the specific router, app.use();mounts middleware for all routes of the app .

router.get is only for defining subpaths. Consider this example:

var router = express.Router();
app.use('/first', router); // Mount the router as middleware at path /first
router.get('/sud', smaller);
router.get('/user', bigger);

So now you do not need to define individual route like '/first/sud'
you can use /first in app then direct it to subpath and you can have multiuple 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s