【问题标题】:How to make modules in nodejs NON-Static?如何使nodejs中的模块成为非静态的?
【发布时间】:2020-03-10 23:07:15
【问题描述】:

我有一个带有节点 js 和静态 Angular 文件的应用程序。我需要 nodejs 来检查带有授权令牌的请求标头。因此,我有一个模块,它检查令牌是否有效,如果是这种情况,用户可以访问以下所有获取方法。 这适用于 app.use(检查令牌的模块)。

但我还需要用户的电子邮件地址,它写在解码后的令牌中。这个电子邮件地址必须可以在 Angular 应用程序中访问。为此,我植入了一个 get-method,它可以由 Angular 应用程序调用并发回电子邮件。

我的问题是,如何以安全的方式获取电子邮件地址。现在我已经编辑了模块并添加了另一个功能。模块伪代码:

Var email = “”; Module.exports = verfiyToken(req, rsp, next) {

  • 获取req参数的Header
  • 检查令牌
  • 如果token有效,则设置email = realEmailFromToken

// 这个不存在,否则 index.js 的以下 get-methods 永远不会被调用。 如果 (next 存在),则调用 next()

返回 doesntMatterBecauseIsNeverReached; }

现在同一模块中的其他功能 Module.exports = getEmail(){

//Email has the right value if the function verifyToken was successful once. That is always the case, because if not, then getEmail can never be called.
Return email;

}

这对我有用,但我认为模块是单例。如果用户 A 成功拨打电话并且在网站中,我会看到问题。在下一步中,用户 B 成功调用网站并拥有经过验证的令牌。现在变量“email”具有用户 B 的电子邮件地址。如果用户 A 现在调用 Angular 中的一个组件,在其中进行了电子邮件调用,那么他将获得用户 B 的电子邮件。

你明白我的问题吗?如何让模块为每个会话创建一个实例?

对不起英语。有什么问题我都会回答的。

最好的问候

【问题讨论】:

    标签: node.js angular module


    【解决方案1】:

    闭包是你的朋友。

    听起来你想做这样的事情。考虑sample-module.js,它导出一个返回函数的函数:

    // Anything declared here is static and visible across all modules
    const moduleGlobalStatic = 'this value is shared by all.';
    
    exports = module.exports = function( a, b, c ) {
      // stuff declare here is invocation-specific
    
      let invocationSpecificStatic = `this is unique to each invocation - a:${a}, b:${b}, c:${c}`;
    
      function doSomething( x , y , z ) {
        // do something with a, b, c, x, y, and z
      }
    
      return doSomething;
    }
    

    用法很简单:

    const doSomething1 = require('sample-module')( 1 , 2 , 3 ) ; const doSomething2 = require('sample-module')( 'alpha' , 'bravo' , 'charlie' );

    doSomething()关闭在上述不同范围内可见的变量。

    • doSomething1doSomething2分享moduleGlobalStatic

    • doSomething2doSomething2 分别为 abc 以及 invocationSpecificStatic 获取自己的值。

    • 每次调用doSomething1doSomething2 时,它们都会获得自己的xyz 的副本。但是,它们的 abcinvocationSpecificStatic 变量在每次调用时都是不变的(除非它们在执行期间修改它们)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-02
      • 1970-01-01
      • 2020-08-06
      • 1970-01-01
      • 2016-05-20
      • 1970-01-01
      • 2019-08-06
      相关资源
      最近更新 更多