我目前正在编写一个快速应用程序,并希望使用我编写的一些自定义中间件,但快递不断抛出问题。
我有一个es6类,它有一个接受正确参数的方法,如下所示:
foo(req, res, next){
console.log('here');
}
然后在我的应用程序中,我告诉快递使用它如下:
const module = require('moduleName');
...
app.use(module.foo);
但是表示不断抛出此错误:
app.use()需要中间件功能
任何帮助将不胜感激。
答案 0 :(得分:1)
此错误始终发生TypeError: app.use() requires middleware functions
由于您没有导出该功能导致其无法访问的原因
尝试从文件
中导出它exports.foo=function(req, res, next){
console.log('here');
next();
}
您也可以使用module.exports
module.exports={
foo:function(req,res,next){
next();
}
}
答案 1 :(得分:1)
解决方案有两个部分。首先使中间件函数成为从模块导出的该类的静态方法。这个函数需要获取你的类的一个实例,并将调用你需要的任何方法。
"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;
然后在您的节点JS / express app服务器中,在需要该模块后,创建您的类的实例。然后将此实例传递给中间件函数。
var Middle = require('./middle');
var middle = new Middle("Sample data for middle to use");
app.use(Middle.middleware(middle));
现在,在每个请求中,您的中间件都可以访问类数据。