繁体   English   中英

如何向我的 Node.js HTTP 请求添加自定义值以供 Express 使用

[英]How can I add a custom value to my Node.js HTTP request for Express to consume

我有一个 Express 服务器正在侦听 Unix 域套接字。 我正在发出 http 请求,如下所示:

 const requestOptions = {socketPath, method, path, headers, _custom: {foo: () => 'bar'}} http.request(requestOptions, responseCb)

并想在我的 Express 路由处理程序中使用_custom

 app.get('/', (req, res) => { console.log(req._custom) })

这可能吗?

编辑: _custom是一个具有功能的 object。

编辑:我标记为正确的答案是我能找到的最佳解决方案,但是它不允许发送对象(这是我真正想要的)。

您可以通过在需要使用req._custom的路由之前在 Express 服务器中添加自定义中间件来将_custom添加到您的req object 中。

 app.use((req, res, next) => { if (req.get('X-Custom-Header')) { // add custom to your request object req._custom = req.get('X-Custom-Header'); } return next(); });

在客户端,您可以添加自定义 header

 let headers = { 'X-Custom-Header': 'my-custom-value' }; const requestOptions = {socketPath, method, path, headers}; http.request(requestOptions, responseCb)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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