繁体   English   中英

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

[英]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

我尝试了很多方法。

  1. 插入'const aUtil = require('./ aUtil')`
  2. 更改为'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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM