【问题标题】:import by module.exports from external file in NodeJS?通过 module.exports 从 NodeJS 中的外部文件导入?
【发布时间】:2021-11-26 03:59:02
【问题描述】:

我正在尝试从另一个文件导入一个函数。我尝试这样做:

main.js:

const oauth2 = require('./utils/oauth2');
function startOAuth() {
  var token = oauth2.OAuth2.getToken();
}

utils/oauth2.js:

module.exports =  (function() {

    window.OAuth2 = {
        
        /**
         * Initialize
         */
        init: function() {
            this._key = "token";
        },
        /**
         * Get Token
         * 
         * @return OAuth2 access token if it exists, null if not.
         */
         getToken: function() {
            try {
                return window['localStorage'][this._key];
            }
            catch(error) {
                return null;
            }
         }
       };
    
    OAuth2.init();
})();

我收到以下错误:

Uncaught TypeError: Cannot read properties of undefined (reading 'getToken')

我做错了什么?为什么 NodeJS 找不到 getToken() 函数? 非常感谢您的帮助!

PS:我知道在这里说我是初学者是错误的,但我是初学者;)

【问题讨论】:

    标签: javascript node.js function


    【解决方案1】:

    您正在导出调用函数而不返回的结果。您分配给 module.exports 的是一种称为 Immediately-invoked-function-expression 的模式。

    如果您将OAuth 分配给一个变量,在声明之后立即调用init(),然后将其导出,代码应该可以工作。

    const OAuth2 = {
      /**
       * Initialize
       */
      init: function () {
        this._key = "";
      },
      /**
       * Get Token
       *
       * @return OAuth2 access token if it exists, null if not.
       */
      getToken: function () {
        try {
          return window["localStorage"][this._key];
        } catch (error) {
          return null;
        }
      },
    };
    
    OAuth2.init();
    
    module.exports = OAuth2;
    

    【讨论】:

    • 您好,非常感谢您的快速答复!现在它运行完美。
    猜你喜欢
    • 2018-03-27
    • 1970-01-01
    • 1970-01-01
    • 2016-11-09
    • 2021-09-28
    • 2019-07-02
    • 2020-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多