【问题标题】:Express middleware run in another context?Express 中间件在另一个上下文中运行?
【发布时间】:2015-05-17 05:31:21
【问题描述】:

我正在为 express 创建一个中间件模块,但在“app.use”中使用时似乎无法让对象属性传递

function test (mytest) {
    this.mytest = mytest;
};

test.prototype.showTest = function (req, res, next) {
    console.log(this.mytest);
    next();
};

var s = new test('foo');

router.post('/login', s.showTest, function (req, res) {
    res.send('test');
});

此代码将输出“未定义”而不是“foo”。我怎样才能让它保留对象属性?

【问题讨论】:

  • s.showTest.bind(s)

标签: javascript node.js express middleware


【解决方案1】:

在创建对象时返回你的函数:

function test (mytest) {
    return function (req, res, next) {
        console.log(mytest);
        next();
    };
};

var s = test('foo');

router.post('/login', s, function (req, res) {
    res.send('test');
});

【讨论】:

  • 代码示例中s.showTest 的定义在哪里。 s 将成为您重新设计的 test() 构造函数中的一个函数,所以我不清楚 s.showTest 的来源。
  • @jfriend00 s.showTest 已被构造函数返回的函数替换。
  • 您的意思是现在您已编辑答案以删除对s.showTest 的引用。此外,没有理由再使用s = new test('foo')。你可以做s = test('foo');。
  • @jfriend00 你知道,我很抱歉我犯了一个错误,但你真的没有增加使用 stackoverflow 已经很酸的内涵。有人犯了一个错误,编辑它并继续。
  • 我指出了你犯的一个重大错误。如果你刚刚说:“谢谢,我现在已经更正了”,一切都会好起来的。但我以为你是在说我的评论有误,而你的错误从未出现过,我对此做出了反应。没关系,我会在其他地方继续前进。
猜你喜欢
  • 1970-01-01
  • 2016-03-31
  • 1970-01-01
  • 1970-01-01
  • 2017-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-29
相关资源
最近更新 更多