N Sharma
N Sharma

Reputation: 34497

Cannot call a class as a function in nodejs express

Hi I am trying to follow ES6 syntax to create a middleware of my node.js application.

index.js

export default class Middleware {
  constructor() {
    //do nothing
  }

  fun1 = (req, res, next) => {
    console.log("------------------------------------");
    console.log("AAa");
    console.log("------------------------------------");
    next();
  };

  fun2 = (req, res, next) => {
    console.log("------------------------------------");
    console.log("AAa");
    console.log("------------------------------------");
    next();
  };
}

app.js

import Middleware from ".index";
app.use(Middleware);

I am getting an error Cannot call a class as a function. Does anyone know what is wrong?

Upvotes: 0

Views: 1534

Answers (1)

alexmac
alexmac

Reputation: 19597

Express app#use expects a function with the following signature:

function(req, res, next) {

To make it work, you need to do:

  1. Create an instance of Middleware class.
  2. Register middleware for each function in the class.

Example:

let middleware = new Middleware();

app.use(middleware.func1);
app.use(middleware.func2);

Upvotes: 4

Related Questions