我如何添加一个自定义值到我的Node.js HTTP请求Express消费



我有一个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是一个具有函数的对象。

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

您可以在需要使用req._custom的路由之前在Express服务器中添加自定义中间件,从而将_custom添加到req对象中。

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();
});

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

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

最新更新