How to write middleware for Express.Js apps

Middleware functions are functions that have access to the request object (req), the response object (res), and the next function in the application’s request-response cycle. The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.

Middleware functions can perform the following tasks:

  • Execute any code.
  • Make changes to the request and the response objects.
  • End the request-response cycle.
  • Call the next middleware in the stack.

Here is an example of a simple “Hello World” Express application.

var express = require('express')
var app = express()

app.get('/', function (req, res) {
  res.send('Hello World!')
})

app.listen(3000)

Middleware function logger

Here is a simple example of a middleware function called “logger”. This function just prints “logged” when a request to the app passes through it.

var logger = function (req, res, next) {
  console.log('logged')
  next()
}

To load the middleware function, call app.use(), specifying the middleware function. The following code loads the logger middleware function before the route to the root path (/). Here is whole code.

var express = require('express')
var app = express()

var logger = function (req, res, next) {
  console.log('logged')
  next()
}

app.use(logger)

app.get('/', function (req, res) {
  res.send('Hello World!')
})

app.listen(3000)

You can also read this

Routing in Node.js with Express.Js

In this post I will try to explain how routing...

app.get('/', function (req, res) {
  res.send('hello from me')
})

Croatia recession prediction

This LSTM recurrent neural network learns to predict Croatia economic...

pred.train_LSTM()
pred.evaluate_LSTM()
pred.display_results(