[英]how to use module in same module file in node js
aUtil.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));
}
}
that function call in test.js 该函数在test.js中调用
router.get('/check', aUtil.isLoggedin, async (req, res) => { ... })
I want to use the function above in that function. 我想在该函数中使用上面的函数。
But I keep getting errors. 但是我不断出错。
ReferenceError: successTrue is not defined
I tried many ways. 我尝试了很多方法。
'res.json(successTrue( ... )'
'res.json(successTrue( ... )'
Use this
: 使用
this
:
module.exports = {
successTrue: function() {
return { foo: 'bar' }
},
isLoggedin: function() {
console.log(this.successTrue())
}
}
You're exporting an object, so this
refers to itself. 您正在导出对象,因此
this
是指自身。
Also make sure you're binding aUtils
if you're using it as middleware like so: 如果像这样将
aUtils
用作中间件,还请确保绑定了aUtils
:
router.get('/check', aUtil.isLoggedin.bind(aUtil), async (req, res) => { ... })
Try this : 尝试这个 :
const aUtil = {
successTrue: function() { //return json obj },
isLoggedin: function() {
res.json(aUtil.successTrue( ... ));
}
}
module.exports = aUtil;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.