Node.js framework express.js middleware All In One
express.js middlewares order
writing middleware
const express = require('express')
const app = express()
const myLogger = function (req, res, next) {
console.log('LOGGED')
next()
}
app.use(myLogger)
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(3000)
https://expressjs.com/en/guide/writing-middleware.html
demos
// const express = require('express')
import express from 'express';
const app = express()
const middleware1 = function (req, res, next) {
console.log(`middleware 1 ✅`)
next()
}
const middleware2 = (req, res, next) => {
console.log(`middleware 2 ✅✅`)
next()
}
const middleware3 = (req, res, next) => {
console.log(`middleware 3 ✅✅✅`)
next()
}
app.use(middleware1)
app.use(middleware2)
app.use(middleware3)
app.get('/', (req, res) => {
res.send('Hello World!');
})
// app.listen(3000)
const PORT = 3000;
app.listen(PORT, () => {
console.log(`server is running on http://localhost:${PORT}`);
})
// const express = require('express')
import express from 'express';
const app = express()
const middleware1 = function (req, res, next) {
console.log(`middleware 1 ✅`)
next()
}
const middleware2 = (req, res, next) => {
console.log(`middleware 2 ✅✅`)
next()
}
const middleware3 = (req, res, next) => {
console.log(`middleware 3 ✅✅✅`)
next()
}
app.use(middleware1, middleware2, middleware3);
app.get('/', (req, res) => {
res.send('Hello World!');
})
// app.listen(3000)
const PORT = 3000;
app.listen(PORT, () => {
console.log(`server is running on http://localhost:${PORT}`);
})