随处访问请求上下文 [英] Access request context anywhere

查看:83
本文介绍了随处访问请求上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Express,每次我使用日志调试和跟踪应用程序时,都需要访问请求中的某些数据(标题,Cookie等).

I'm using Express and I need to access some data that it is on the request (headers, cookies, etc) every time I use the log to debug and trace my app.

使用其他语言(例如Java),我可以在其中放置数据,并在每次记录某些内容时都可以访问它.但是据我所知,使用NodeJS并没有这种事情,因为我们只有一个线程.

With other languages (ie: Java) I have the "Thread Context" where I can put that data, and so access it whenever I log something. But with NodeJS there is no such thing, as far as I know, because we have only one thread.

我试图避免在每个函数中传递req变量,以便我可以记录该信息.

I'm trying to avoid passing the req variable in every function so I can log that info.

是否有节点或expressjs功能可让我随时随地获取数据?

Is there a node or expressjs feature that let me get the data anywhere?

推荐答案

JavaScript是单线程的事实不是一个限制,并且不会阻止使用线程上下文"作为使用可普遍访问的状态"的方式.问题会在进行异步调用后立即开始,并且状态不再符合您的预期.

The fact that JavaScript is single threaded is not a limitation and doesn't prevent using "Thread Context" as a means to use "universally accessible state". The problems will start as soon as asynchronous calls are made and the state no longer matches what you intend it to be.

这是为什么全局状态被认为是不良习惯"的原因之一,您应该避免使用它(不是特别在使用JavaScript和/或Node进行开发时...).

This is one of the reasons why global state is considered "bad habit" and you should aim to avoid it (not specifically when developing in JavaScript and/or Node...).

相反,您应该应该绕过一个对象,但不能绕过req.您应该以这样的方式构造对象或调用函数:与每个调用链相关的log实例(从request事件开始,并通过所有内部调用)都可以传递.该log实例应使用记录所需的任何上下文进行初始化,并且在您的情况下,应使用原始req的请求详细信息.

Instead, you should pass around an object, but not req. You should construct your objects or call your functions in such a way that the log instance that's relevant to every call chain (starting at the request event and through all internal calls) is passed around. That log instance should be initialized with whatever context of required for logging, and in your case, the request details from the original req.

这篇关于随处访问请求上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆