【问题标题】:Cannot call a class as a function in nodejs express无法在nodejs express中将类作为函数调用
【发布时间】:2017-10-03 14:08:19
【问题描述】:

您好,我正在尝试遵循 ES6 语法来创建我的 node.js 应用程序的中间件。

index.js

export default class Middleware {
  constructor() {
    //do nothing
  }

  fun1 = (req, res, next) => {
    console.log("------------------------------------");
    console.log("AAa");
    console.log("------------------------------------");
    next();
  };

  fun2 = (req, res, next) => {
    console.log("------------------------------------");
    console.log("AAa");
    console.log("------------------------------------");
    next();
  };
}

app.js

import Middleware from ".index";
app.use(Middleware);

我收到一个错误,无法将类调用为函数。有谁知道怎么回事?

【问题讨论】:

  • 哪一行给出了错误?
  • 当我删除 app.use(Middleware); 然后它工作
  • 这是用express框架吗?
  • 调用类的时候要加上new关键字,试试app.use(new Middleware);
  • 它告诉你想错了——你不能在这里使用一个类。 app.use() 期待具有特定签名的函数。

标签: javascript node.js express ecmascript-6


【解决方案1】:

Express app#use 需要一个具有以下签名的函数:

function(req, res, next) {

要让它发挥作用,你需要做:

  1. 创建Middleware 类的实例。
  2. 为类中的每个函数注册中间件。

例子:

let middleware = new Middleware();

app.use(middleware.func1);
app.use(middleware.func2);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-25
    • 2020-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-10
    • 2018-04-16
    • 2020-04-19
    相关资源
    最近更新 更多