How to use Express Middleware

Setting Up An Express Server

const express = require('express')
const app = express()

app.get('/', (req, res) => {
res.send('Home Page')
})

app.get('/users', (req, res) => {
res.send('Users Page')
})

// Start the Server
app.listen(4000, ()=>{ console.log(`server running on port 4000`)})

What Is Middleware?

Create a Logging Middleware

const express = require('express')
const app = express()

app.get('/', (req, res) => {
res.send('Home Page')
})

app.get('/users', (req, res) => {
res.send('Users Page')
})

function loggingMiddleware(req, res, next) {
console.log('Inside Middleware')
}
// Start the Server
app.listen(4000, ()=>{ console.log(`server running on port 4000`)})
const express = require('express')
const app = express()

app.use(loggingMiddleware)
app.get('/', (req, res) => {
res.send('Home Page')
})

app.get('/users', (req, res) => {
res.send('Users Page')
})

function loggingMiddleware(req, res, next) {
console.log('Inside Middleware')
}
// Start the Server
app.listen(4000, ()=>{ console.log(`server running on port 4000`)})
const express = require('express')
const app = express()

app.use(loggingMiddleware)

app.get('/', (req, res) => {
res.send('Home Page')
})

app.get('/users', (req, res) => {
res.send('Users Page')
})

function loggingMiddleware(req, res, next) {
console.log('Inside Middleware')
next()
}
// Start the Server
app.listen(4000, ()=>{ console.log(`server running on port 4000`)})
const express = require('express')
const app = express()

app.use(loggingMiddleware)

app.get('/', (req, res) => {
res.send('Home Page')
})

app.get('/users', (req, res) => {
res.send('Users Page')
})

function loggingMiddleware(req, res, next) {
console.log(`${new Date().toISOString()}: ${req.originalUrl}`)
next()
}
// Start the Server
app.listen(4000, ()=>{ console.log(`server running on port 4000`)})

Conclusion

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

From React to Composi-Part 5

React Native Bootcamp Öğrencilerimizden

How to Use RxJS debounceTime with Angular

How to Connect CircleCI With Netlify

connecting CircleCI to Netlify

Javascript sort array of objects

Manual Moderation

Templating in Electron

You don’t need JWT anymore

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
Pratik Kumar

Pratik Kumar

More from Medium

Grammarly application

application error a client-side exception has occurred in Next.js

OCS Inventory 2.9.1 XSS Stored + Hijack Session (CVE-2021-46355)

REST Services