Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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();
  }
}

Solution 2:

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";

classMiddle {
  constructor(message) {
    this._message = message;
  }

  staticmiddleware(middle) {

    returnfunctionmiddleHandler(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 requestnext();
    };
  }

  // instance methodsonStart(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.

Post a Comment for "Node Express Middleware"