Middleware
what is middleware
- a function that takes a request object and either terminates the request/response cycle or passes control to another middleware function
const express = require('express');
const app = express();
app.use((req, res, next) => {
console.log('Time:', Date.now());
next();
})
expresss middlewares
app.use(express.json()); //express middleware to parse json object such as in req.body
app.use(express.urlencoded({extended:true})); //express middleware to parse incoming request with URL payloads ?key=value
app.use(express.static('public')); //express middleware to serve static files (e.g. served at localhost:3001/readme.txt)
third party middlewares
app.use(helmet()); //third party middleware to secure response header
app.use(morgan('tiny')); //third party middleware to log requests
Error Handling Middleware
- Inside middleware folder, create a file called
errorHandler.js
const errorHandler = (err,req,res,next) =>{
console.log(err.stack);
res.status(500).json({
success:false,
error:err.message
});
}
module.exports = errorHandler;
//then in the app.js, we need to use this middleware
const errorHandler = require('./middleware/error');
//use this middleware after all the routes and controllers
app.use(errorHandler);
TryCatch Handler middleware
- This avoid repeating the try/catch code in each route
- Inside the middleware folder create a file called
trycatchHandler.js
const trycatchHandler = fn => (req,res,next) =>
Promise
.resolve(fn(req,res,next))
.catch(next)
module.exports = asyncHandler;
//then we can use it in each route by wrapping async inside the middleware
const trycatchHandler = require('../middleware/trycatchHandler');
router.get('/', trycatchHandler( async (req,res,next)=>{
const result = await Product.find();
res.status(200).json({success:true,count:result.length,data:result});
}))
Replace TryCatchHandler with express-async-errors
$ npm i express-async-errors
//then we can remove trycatchHandler in all routes
router.get('/', async (req,res,next)=>{
const result = await Product.find();
res.status(200).json({success:true,count:result.length,data:result});
});