Answer the question
In order to leave comments, you need to log in
Why is the class instance context lost?
Good afternoon. This question stems from another question . Here is the class code:
class Authorized {
constructor() {
this.jwt = require('jsonwebtoken')
this.secretKey = 'dSjkLsSjerIfkL'
}
createSign(data, secretKey){
console.log('create data', this)
return this.jwt.sign(data,secretKey)
}
isAuthorized(req, res, next){
console.log('isAuth',this)
next()
}
Answer the question
In order to leave comments, you need to log in
Because it is used as a middleware.
Call it by binding content, something like this
const Authorized = require('../moduls/authorized')
const auth = new Authorized();
// так
router.get("path/",auth.isAuthorized.bind(auth));
// или так
router.get("path/",(...a)=>auth.isAuthorized(...a));
isAuthorized(){
return (req, res, next)=>{
console.log('isAuth',this)
// тут код мидлвара
}
}
router.get("path/",auth.isAuthorized());
// или
router.post("path/",auth.isAuthorized());
// или
router.use(auth.isAuthorized());
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question