Node Express中间件 [英] Node Express Middleware

查看:118
本文介绍了Node Express中间件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am currently writing an express app and want to use some custom middleware that I have written however express keeps throwing an issue.

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

I have a es6 class that has a method that accepts the correct parameters like below:

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

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

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

then in my app i am telling express to use it like so: const module = require('moduleName'); ... app.use(module.foo);

但express不断抛出此错误:

but express keeps throwing this error:

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

app.use() requires middleware functions

任何帮助将不胜感激.

any help would be greatly appreciated.

推荐答案

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

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;

然后在您的节点JS/express应用服务器中,在需要该模块之后,创建您的类的实例.然后将此实例传递给中间件功能.

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.

这篇关于Node Express中间件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆