繁体   English   中英

Node Express中间件

[英]Node Express Middleware

我目前正在编写一个Express应用程序,并且想使用我编写的一些自定义中间件,但是Express总是引发问题。

我有一个es6类,该类具有接受如下所示正确参数的方法:

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

然后在我的应用中,我告诉express要像这样使用它: const module = require('moduleName'); ... app.use(module.foo); const module = require('moduleName'); ... app.use(module.foo);

但express不断抛出此错误:

app.use()需要中间件功能

任何帮助将不胜感激。

总是发生此错误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();
  }
}

解决方案包括两个部分。 首先,使中间件功能成为您从模块中导出的该类的静态方法。 此函数需要使用您的类的实例,并将调用您需要的任何方法。

"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应用服务器中,在需要模块之后,创建您的类的实例。 然后将此实例传递给中间件函数。

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

现在,根据每个请求,您的中间件都可以访问类数据。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM