[英]how to use module in same module file in node js
aUtil.js
module.exports = {
successTrue: function(data) {
return { data: data, success: true };
},
isLoggedin: async (req, res) {
//decoded token in req header
//if decoded token success,
res.json(this.successTrue(req.decoded));
}
}
该函数在test.js中调用
router.get('/check', aUtil.isLoggedin, async (req, res) => { ... })
我想在该函数中使用上面的函数。
但是我不断出错。
ReferenceError: successTrue is not defined
我尝试了很多方法。
'res.json(successTrue( ... )'
使用this
:
module.exports = {
successTrue: function() {
return { foo: 'bar' }
},
isLoggedin: function() {
console.log(this.successTrue())
}
}
您正在导出对象,因此this
是指自身。
如果像这样将aUtils
用作中间件,还请确保绑定了aUtils
:
router.get('/check', aUtil.isLoggedin.bind(aUtil), async (req, res) => { ... })
尝试这个 :
const aUtil = {
successTrue: function() { //return json obj },
isLoggedin: function() {
res.json(aUtil.successTrue( ... ));
}
}
module.exports = aUtil;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.