0

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.

1
  • foo(req, res, next){ console.log('here'); } ? Commented Oct 8, 2016 at 11:53

2 Answers 2

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(); } } 
Sign up to request clarification or add additional context in comments.

4 Comments

This works but then I lose access to the class methods. Is there not a way to use class methods as middleware?
you can take a look here how to access class method stackoverflow.com/questions/11782453/class-methods-in-node-js
The class code is similar to this, (sorry can't show the exact code as it's for a clients application). pastebin.com/dTdseg3L where bar would be the method I want to use as middleware
no one can guess what exactly happening with you until see your code
1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.