简体   繁体   English

Node Express中间件

[英]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. 我目前正在编写一个Express应用程序,并且想使用我编写的一些自定义中间件,但是Express总是引发问题。

I have a es6 class that has a method that accepts the correct parameters like below: 我有一个es6类,该类具有接受如下所示正确参数的方法:

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

but express keeps throwing this error: 但express不断抛出此错误:

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

any help would be greatly appreciated. 任何帮助将不胜感激。

This error always occurs TypeError: app.use() requires middleware functions 总是发生此错误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

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

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. 然后,在您的节点JS / express应用服务器中,在需要模块之后,创建您的类的实例。 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. 现在,根据每个请求,您的中间件都可以访问类数据。

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

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