-1

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...
Epple
  • 640
  • 14
  • But also there's really no point using a class there. – jonrsharpe Jun 30 '23 at 17:56
  • 1
    this error occurring because the this context is not properly bound when calling this.handleMiddleware(req, res) within the applyMiddleware method. To resolve this issue, you can use the bind method to bind the correct this context to the handleMiddleware function or use arrow function – Humberto Barbosa Jun 30 '23 at 17:59

1 Answers1

2

The problem is that this is not preserved which causes error when you invoke it, So to resolve this issue you could use an arrow function:

handleMiddleware = (req, res) => {
    //code...
}

Or you can use the .bind(this) method to bind the correct this context when you call the function:

handleMiddleware(req, res) {
console.log('handleMiddleware Request and Response:', req, res);
}

applyMiddleware(req, res, next) {
    console.log(req, res);
    this.handleMiddleware.bind(this)(req, res);
    next();
}
XMehdi01
  • 5,538
  • 2
  • 10
  • 34
  • thank you very much, but I have a question: Do we really need to use classes in JS platform like Nodejs? – Epple Jun 30 '23 at 18:08