我正在尝试从IncomingMessage
异步钩子提供的实例中获取 HTTP 标头和 HTTP 正文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();
我已经深入研究了 Node.js 源代码,但没有运气。我找不到填充的代码req.headers
,也找不到创建 HTTP 正文流的代码。
编辑
总体目标是使通配符 API能够提供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);
}