I am using class to implement middleware in ExpressJS but I am getting a problem when calling methods. Firstly, I am running the following code below and then I still received res
and req
objects from applyMiddleware
but in the handleMiddleware
method I trying to get req
and res
but it will lead to the error:
TypeError: Cannot read properties of undefined (reading 'MyMiddleware')
why am i getting this error? And what is the cause of this error? It seems to only happen with classes and not with functions.
my code:
class MyMiddleware {
constructor() {}
handleMiddleware(req, res) {
// cannot get req & req
console.log('Request incoming: ', req);
console.log('Response outcoming: ', res);
}
applyMiddleware(req, res, next) {
console.log(req, res); // oke, everything is printed
this.handleMiddleware(req, res);
next();
}
}
export default MyMiddleware;
Applying the middleware above in Express:
const app = express();
const middleware = new MyMiddleware();
app.use(middleware.applyMiddleware)
...more code...