Express middleware issue | Sololearn: Learn to code for FREE!


Express middleware issue

Check the code and tell me why the middleware is throwing error but when i use it inside function it works perfectly.

6/15/2020 12:28:14 AM


3 Answers

New Answer


Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function (next) in the application’s request-response cycle. Middleware is accountable for calling the next middleware by making call function of next(), before it can pass req and res to the next function. auth.js middleware should be in this format module.exports = function(req,res,next) { if (req.session.role === 'admin') { next(); // responsible for triggering next function call } else { res.render('unauthorized'); // not go to next function } } before you can use it as const auth = require('../auth/auth'); app.get("./auth', auth, (req,res) => { res.render('protected'); // next function execution here (passing req,res) }


JWT tutorial


Well, yes what you've said i know. I was trying to use the class method instead of a regular function. I have found that it works only in the function format. Thanks for the suggestion. function authenticate(req, res, next){ adminAuth.authenticate(req, res, next); }