问题:
有没有办法在每个会话/http 请求中创建变量存储?该变量必须是全局可访问的,并且每个 HTTP 请求/连接/会话都不同,并且不需要在函数之间传递。
例如(只是为了说明):
setVariableThatCanBeAccessedByThisHTTPRequestOnly( 'a string data' );
任何东西都应该有效,但我宁愿远离将其从一个函数传递到另一个函数。
//I'm trying to get rid of passing req parameter to all custom functions.
//I'd like to store it in a variable somehow, that it can be accessed globally, but only within that session/request.
exports.functionName = function( req, res ) {
customFunctionThatRequiresReq( req );
};
最初的问题
我最近一直在使用 Node.js,并且对其 GLOBAL 范围有点担心。假设我们有一个 server.js 文件:
username = ""; //Global scope
然后当连接建立并且服务器收到请求时,它将执行以下操作:
username = selectUsernameWithConditions(); //This will return a username
我的问题是:如果两台不同的计算机向服务器发送请求,则值username
独立不同?我的意思是,是否username
当第一个请求的处理方式与username
当处理第二个请求时,或者它们只是一个变量并且将被覆盖?
如果它们被覆盖,存储数据并使它们仅在该请求和/或会话中全局访问的最佳方式是什么?例如,以下代码:
username = selectUsernameWithConditions(); //This will return a username
将分配username
针对不同的请求采取不同的方式,并且不会相互覆盖。