tvance
tvance

Reputation: 83

Node Express Middleware

I am currently writing an express app and want to use some custom middleware that I have written however express keeps throwing an issue.

I have an es6 class that has a method that accepts the correct parameters like below:

foo(req, res, next){
   console.log('here');
}

then in my app I am telling express to use it like so:

const module = require('moduleName');
...
app.use(module.foo);

but express keeps throwing this error:

app.use() requires middleware functions

any help would be greatly appreciated.

Upvotes: 0

Views: 1994

Answers (2)

Bryan
Bryan

Reputation: 1153

The solution has two parts. First make the middleware function a static method of that class that you export from your module. This function needs to take an instance of your class and will invoke whatever methods you need to.

"use strict";

class Middle {
  constructor(message) {
    this._message = message;
  }

  static middleware(middle) {

    return function middleHandler(req, res, next) {
      // this code is invoked on every request to the app

      // start request processing and perhaps stop now.
      middle.onStart(req, res);

      // let the next middleware process the request
      next();
    };
  }

  // instance methods
  onStart(req, res) {
    console.log("Middleware was given this data on construction ", this._message);
  }
}

module.exports = Middle;

Then in your node JS / express app server, after requiring the module, create an instance of your class. Then pass this instance into the middleware function.

var Middle = require('./middle');
var middle = new Middle("Sample data for middle to use");
app.use(Middle.middleware(middle));

Now on every request your middle ware runs with access to the class data.

Upvotes: 1

abdulbari
abdulbari

Reputation: 6232

This error always occurs TypeError: app.use() requires middleware functions

Since you are not exporting that function that's why it's unreachable

try to export it like this from file

exports.foo=function(req, res, next){
   console.log('here');
   next();
}

You can also use module.exports

module.exports={
  foo:function(req,res,next){
    next();
  }
}

Upvotes: 1

Related Questions