如何在节点js的同一模块文件中使用模块

时间:2019-01-25 07:24:33

标签: javascript 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

我尝试了很多方法。

  1. 插入'const aUtil = require('./ aUtil')`
  2. 更改为'res.json(successTrue( ... )'

2 个答案:

答案 0 :(得分:3)

使用['Class' => ..., 'id' => ...]

this

您正在导出对象,因此module.exports = { successTrue: function() { return { foo: 'bar' } }, isLoggedin: function() { console.log(this.successTrue()) } } 指向自身。

如果您将this用作中间件,请确保将其绑定,例如:

aUtils

答案 1 :(得分:2)

尝试一下:

const aUtil = {
    successTrue: function() { //return json obj },
    isLoggedin: function() { 
        res.json(aUtil.successTrue( ... ));
    }
}
module.exports = aUtil;
相关问题