在中间件中调用对象函数
Calling object functions in middleware
我的中间件中有这段代码:
const UserMiddleware = {
isNumber(n) { return !Number.isNaN(parseFloat(n)) && !Number.isNaN(n - 0); },
// eslint-disable-next-line consistent-return
validateSignUp(req, res, next) {
const allSignUpErrors = [];
console.log(this.isNumber(5));
if (this.isNumber(req.body.first_name)) {
allSignUpErrors.push('First name must be a text value');
}
if (allSignUpErrors.length !== 0) {
return res.status(400).json({
status: 400,
error: allSignUpErrors,
});
}
next();
},
我通常使用'this.'调用对象中的函数和变量没有问题。我怀疑中间件中的 'next()' 函数是导致我在使用 'this.' 调用函数时出现以下错误的原因。
TypeError: Cannot read property 'isNumber' of undefined
我试过使用'bind'调用函数,但仍然出现'undefined'错误。
'next()' 函数是否破坏了正常功能?有没有办法正确使用'this.'调用中间件中的函数?
变化:
this.isNumber(...)
至:
UserMiddleware.isNumber(...)
中间件函数中 this
的值将不是您的 UserMiddleware
对象,除非您在将其作为中间件传递时专门使用 .bind()
或某些类似技术。
如需更多选项的帮助,请向我们展示您使用的代码 validateSignUp()
。
例如,如果您正在做:
app.use(UserMiddleware.validateSignUp);
然后,您可以使用 .bind()
为 this
设置所需的值,如下所示:
app.use(UserMiddleware.validateSignUp.bind(userMiddleware));
将 UserMiddleware.validateSignUp
传递给函数会立即失去与 UserMiddleware
对象的关联,调用该函数时的 this
值将由调用者调用函数的方式和不会是 UserMiddleware
对象。使用 .bind(UserMiddleware)
强制设置所需的 this
值。 .bind()
实际上创建了一个包装函数,它的唯一工作是重新附加所需的 this
值,并且该包装函数是作为中间件处理程序传递的。中间件基础结构使用错误的 this
值调用包装函数,然后包装函数使用所需的 this
值调用您的 validateSignUp
函数 - 可能使用 .apply()
.
要了解 .bind()
的工作原理,您可以查看它的 polyfill here on MDN. For more of a discussion of how the value of this
is set, see Six ways of setting this
。
我的中间件中有这段代码:
const UserMiddleware = {
isNumber(n) { return !Number.isNaN(parseFloat(n)) && !Number.isNaN(n - 0); },
// eslint-disable-next-line consistent-return
validateSignUp(req, res, next) {
const allSignUpErrors = [];
console.log(this.isNumber(5));
if (this.isNumber(req.body.first_name)) {
allSignUpErrors.push('First name must be a text value');
}
if (allSignUpErrors.length !== 0) {
return res.status(400).json({
status: 400,
error: allSignUpErrors,
});
}
next();
},
我通常使用'this.'调用对象中的函数和变量没有问题。我怀疑中间件中的 'next()' 函数是导致我在使用 'this.' 调用函数时出现以下错误的原因。
TypeError: Cannot read property 'isNumber' of undefined
我试过使用'bind'调用函数,但仍然出现'undefined'错误。
'next()' 函数是否破坏了正常功能?有没有办法正确使用'this.'调用中间件中的函数?
变化:
this.isNumber(...)
至:
UserMiddleware.isNumber(...)
中间件函数中 this
的值将不是您的 UserMiddleware
对象,除非您在将其作为中间件传递时专门使用 .bind()
或某些类似技术。
如需更多选项的帮助,请向我们展示您使用的代码 validateSignUp()
。
例如,如果您正在做:
app.use(UserMiddleware.validateSignUp);
然后,您可以使用 .bind()
为 this
设置所需的值,如下所示:
app.use(UserMiddleware.validateSignUp.bind(userMiddleware));
将 UserMiddleware.validateSignUp
传递给函数会立即失去与 UserMiddleware
对象的关联,调用该函数时的 this
值将由调用者调用函数的方式和不会是 UserMiddleware
对象。使用 .bind(UserMiddleware)
强制设置所需的 this
值。 .bind()
实际上创建了一个包装函数,它的唯一工作是重新附加所需的 this
值,并且该包装函数是作为中间件处理程序传递的。中间件基础结构使用错误的 this
值调用包装函数,然后包装函数使用所需的 this
值调用您的 validateSignUp
函数 - 可能使用 .apply()
.
要了解 .bind()
的工作原理,您可以查看它的 polyfill here on MDN. For more of a discussion of how the value of this
is set, see Six ways of setting this
。