I'm trying to get the HTTP headers and the HTTP body from the IncomingMessage
instance provided by the async hook HTTPINCOMINGMESSAGE
:
import asyncHooks = require("async_hooks");
import { IncomingMessage } from "http";
asyncHooks.createHook({
init: (
asyncId: number,
type: string,
triggerAsyncId: number,
req: IncomingMessage
) => {
if (type !== "HTTPINCOMINGMESSAGE") return;
// Where are the HTTP headers?
console.log(req.headers); // prints `undefined`
// How do I get the HTTP body?
console.log(req.on); // prints `undefined`
// Yet, `req` is an `IncomingMessage`, the same than following `req`:
//
// const http = require('http');
// http.createServer((req, res) => {
// // The HTTP request headers are available here!
// console.log(req.headers);
// // `req` is an `IncomingMessage` as well
// console.log(req.constructor===IncomingMessage); // prints `true`
// });
//
console.log(req.constructor===IncomingMessage); // prints `true`
},
})
.enable();
I've digged into the Node.js source code, but no luck. I can't find the code that populates req.headers
, nor the code that creates the HTTP body stream.
Edit
The overarching goal is to enable Wildcard API to provide a context
:
import { context } from '@wildcard-api/server';
// Wildcard saves a cookie on behaf of the Wildcard user, and exposes
// the value saved in the cookie over an ES6 proxy `context`.
function called_somewhere_within_an_http_request_lifecycle() {
// Wildcard uses Async Hooks to be able to know the HTTP request associated
// with the following `context.userName` ES6 proxy getter call, and therefore
// can provide the value `userName` saved in the cookie of the HTTP request.
console.log(context.userName);
}