Last active
September 5, 2021 08:18
-
-
Save yurynix/44fc128217e326e4e3201dd5592a6cdc to your computer and use it in GitHub Desktop.
Monkey patch node's http client to print outgoing requests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const originalEnd = require('http').ClientRequest.prototype.end; | |
require('http').ClientRequest.prototype.end = function() { | |
try { | |
const headersSymbol = Object.getOwnPropertySymbols(this).find(k => k.toString().includes('kOutHeaders')) | |
const host = this[headersSymbol]['host'][1]; | |
let protocol = this.agent && this.agent.protocol ? this.agent.protocol : 'unknown:' | |
if (!this.agent && this[headersSymbol]['upgrade']) { | |
protocol = 'ws:'; | |
} | |
const url = `${protocol}//${host}${this.path}`; | |
const method = this.method; | |
console.log(`Outgoing request: ${JSON.stringify({ | |
url, | |
method, | |
})}`); | |
} catch(ex) { | |
console.log(`Failed to report request: ${ex}`) | |
} | |
return originalEnd.apply(this, arguments); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ever wanted to inspect outgoing http requests from a node app?
We can simply monkey patch http client! 😉
For example, if you'd like to see what
yarn
is requesting, run (after saving the script above asinspect-outgoing-http.js
):