我如何添加一个自定义值到我的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是一个function的对象。

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

您可以在需要使用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)