使用Express.js时,Node.js ES6类无法从类方法中调用类方法 [英] Node.js ES6 Class unable to call class method from within class method when using Express.js

查看:442
本文介绍了使用Express.js时,Node.js ES6类无法从类方法中调用类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Nb。。这让我有点发疯了,我去过屋子几次。但是,我对ES6和JS整体来说还很陌生,并且完全理解JS类与其他语言中的类不一样,并且可能会完全错误地解决。

Nb. This is driving me a little nuts and I've been around the houses a few times. However I'm fairly new to ES6 and JS as a whole and fully understand that a JS Class is not like that of Classes found in other languages and might be approaching this completely wrong.

我正在运行以下代码,该代码在Node v8.9.0上使用Express.js(v4.16.3)和body-parser(v1.18.2)。

I'm running the following code which is using Express.js (v4.16.3) and body-parser (v1.18.2) on Node v8.9.0.

app.post('/api/v1/user/update', urlencodedParser, user.update);

代码调用 urlencodedParser,它充当中间件,为 req提供 req.body以便我可以提取表单字段。 用户是一个已导出的类模块,包含用于验证,更新等的所有功能,并且看起来像这样:

The code calls 'urlencodedParser' which is acting as middleware to provide 'req' with 'req.body' so that I can pull out the form fields. 'user' is a class module that has been exported and contains all the functions for validation, updating etc. and looks something like this:

class Users {    
    update(req,res) {
        console.log('updating...');
        this.verifyUserIdentity();
    }

    verifyUserIdentity(req,res) {
        console.log('verify');
    }
}

module.exports = new Users;

现在,如果我要在不使用Express的节点中运行此代码,例如:

Now if I were to run this code in node without Express like so:

var users = require('./modules/users');

users.update();

这一切似乎都执行了,我在CLI上得到了以下输出:

It all appears to execute and I get the following output on the CLI:

updating...
verify

如果我将其全部包装在 app.post()中(如上)并使用Postman发送POST,它将执行第一个方法并在控制台后停止运行.log(),没有错误。似乎没有调用 verifyUserIdentity(),并且在CLI上得到了以下信息:

If I wrap it all up in the app.post() (above) and use Postman to send a POST it executes the first method and stops dead after the console.log() with no error. It seems not to call verifyUserIdentity() and I get the following on the CLI:

updating...

如果我按照下面的方式修改代码并将一系列方法传递给Express的中间件处理程序,它似乎可以工作,但是现在我必须分别调用 verifyUserIdentity(),并且不能解决如何从同一类调用另一个方法的问题,例如 log()方法。

If I modify the code as you see below and pass an array of methods to Express' middleware handler, it seems to work, but now I have to call verifyUserIdentity() separately, and doesn't solve the problem of how do I call another method from the same class, for instance a log() method.

class Users {    
    update(req,res) {
        console.log('updating...');
    }

    verifyUserIdentity(req,res,next) {
        console.log('verify');
        next();
    }
}

module.exports = Users;



app.post('/api/v1/user/update', [urlencodedParser, users.verifyUserIdentity], users.update);

我的问题:
-为什么原始模式无法在Express上使用?
-由于回调处理程序,这样做加息了吗?
-这与Node v8.9.0有关吗?
-我做错了吗?

Some my question: - Why isn't the original pattern working with Express? - has 'this' taken a hike because of the callback handlers? - Has this got something to do with Node v8.9.0? - Am I doing this all wrong?

推荐答案

您没有得到正确的这个指针。

You aren't getting a proper this pointer in your method.

更改以下代码行:

app.post('/api/v1/user/update', urlencodedParser, user.update);

为此:

app.post('/api/v1/user/update', urlencodedParser, user.update.bind(user));

当您通过 user.update 时,全部它传递的是对 update()方法的引用,并且与 user 对象的关联丢失。当Express然后将其作为常规函数调用时,该方法中的 this 将为 undefined (在严格模式下),而不是您的 user 对象。您可以使用 .bind()来解决此问题,如上所示。

When you pass user.update, all it passes is a reference to the update() method and the associate with the user object is lost. When Express then calls it as a normal function, this will be undefined (in strict mode) inside that method rather than your user object. You can use .bind() to solve this issue as shown above.

仅供参考,这没有专门针对与快递。当传递对 obj.method 的引用作为您想要存储一些代码然后稍后调用的回调时,这是一个通用问题。您必须将对象绑定到它,以便在正确的对象上下文中调用它。

FYI, this has nothing specifically to do with Express. It's a generic issue when passing a reference to an obj.method as a callback that you want some code to store and then call later. You have to "bind" the object to it so that it gets called with the right object context.

这篇关于使用Express.js时,Node.js ES6类无法从类方法中调用类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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