Lio*_*son 1 node.js express es6-class
铌。这让我有点发疯,我已经在房子周围几次了。但是,我对 ES6 和 JS 整体还是很陌生,并且完全理解 JS 类与其他语言中的类不同,并且可能完全错误地处理这个问题。
我正在运行以下代码,该代码在 Node v8.9.0 上使用 Express.js (v4.16.3) 和 body-parser (v1.18.2)。
app.post('/api/v1/user/update', urlencodedParser, user.update);
Run Code Online (Sandbox Code Playgroud)
代码调用“urlencodedParser”,它充当中间件,为“req”提供“req.body”,以便我可以提取表单字段。'user' 是一个已导出的类模块,包含所有用于验证、更新等的功能,看起来像这样:
class Users {
update(req,res) {
console.log('updating...');
this.verifyUserIdentity();
}
verifyUserIdentity(req,res) {
console.log('verify');
}
}
module.exports = new Users;
Run Code Online (Sandbox Code Playgroud)
现在,如果我要在没有 Express 的节点中运行此代码,如下所示:
var users = require('./modules/users');
users.update();
Run Code Online (Sandbox Code Playgroud)
这一切似乎都在执行,我在 CLI 上得到以下输出:
updating...
verify
Run Code Online (Sandbox Code Playgroud)
如果我将它全部打包在app.post()(上面)中并使用 Postman 发送 POST,它会执行第一个方法并在console.log()之后停止,没有错误。似乎没有调用verifyUserIdentity()并且我在 CLI 上得到以下信息:
updating...
Run Code Online (Sandbox Code Playgroud)
如果我修改下面的代码并将一组方法传递给 Express 的中间件处理程序,它似乎可以工作,但现在我必须单独调用verifyUserIdentity(),并没有解决如何调用另一个的问题来自同一类的方法,例如log()方法。
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);
Run Code Online (Sandbox Code Playgroud)
我的一些问题: - 为什么原始模式不能与 Express 一起使用?- 'this' 是否因为回调处理程序而上涨?- 这与 Node v8.9.0 有关系吗?- 我做错了吗?
您没有this在您的方法中获得正确的指针。
更改这行代码:
app.post('/api/v1/user/update', urlencodedParser, user.update);
Run Code Online (Sandbox Code Playgroud)
对此:
app.post('/api/v1/user/update', urlencodedParser, user.update.bind(user));
Run Code Online (Sandbox Code Playgroud)
当您传递 时user.update,它传递的只是对update()方法的引用,并且与user对象的关联将丢失。当 Express 然后将它作为普通函数调用时,this将undefined(在严格模式下)在该方法而不是您的user对象中。您可以使用.bind()如上所示解决此问题。
仅供参考,这与 Express 没有特别关系。将引用obj.method作为回调传递给 an 时,这是一个通用问题,您希望存储一些代码然后稍后调用。您必须将对象“绑定”到它,以便使用正确的对象上下文调用它。
| 归档时间: |
|
| 查看次数: |
766 次 |
| 最近记录: |