Skip to content

Instantly share code, notes, and snippets.

@ivarconr
Created October 31, 2018 11:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivarconr/c6a881e03f1e0f7bc02e5800eeb71017 to your computer and use it in GitHub Desktop.
Save ivarconr/c6a881e03f1e0f7bc02e5800eeb71017 to your computer and use it in GitHub Desktop.
const http = require('http');
const fetch = require('node-fetch');
const async_hooks = require('async_hooks');
const context = new Map();
const middleware = (req, res) => {
const id = async_hooks.executionAsyncId();
const headers = req.headers;
context.set(id, headers);
res.on('finish', () => context.delete(id));
};
const getHeadersFromContext = () => {
return context.get(async_hooks.executionAsyncId());
};
http.createServer((req, res) => {
middleware(req, res);
//route handler of some sort
handleReq(req, res);
}).listen(5000);
function handleReq(req, res) {
// Somewhere else in app
const headers = getHeadersFromContext();
fetch('http://localhost:3000', {
headers: { 'User-Agent': headers['user-agent'] },
}).then(r => {
res.end('hello\n');
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment