Entonces, estoy tratando de usar algunas API en node.js usando node-fetch y me gustaría registrar la solicitud final que se envía al servidor, pero no puedo encontrar ninguna forma de hacerlo. ¿Puedes ayudarme por favor? Aquí está el código:
const fs = require('fs'); const fetch = require('node-fetch'); const https = require('https'); const reqUrl = 'https://endpoint.com'; const headers = { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Digest': 'SHA-256=47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=', 'Date': 'Sat, 20 Mar 2021 15:42:18 GMT', 'X-Request-ID': 'request_id', 'Authorization': 'Bearer my_bearer', 'Signature': 'my_signature' }; const certs = { key: fs.readFileSync('path_to_key'), cert: fs.readFileSync('path_to_cert') }; async function getAccounts() { const options = { cert: certs.cert, key: certs.key, rejectUnauthorized: false }; const sslConfiguredAgent = new https.Agent(options); try { // here is the problem. How to view the final request header? fetch(reqUrl, { method: 'GET', headers: headers, agent: sslConfiguredAgent }).then(response => { const headers = response.headers; console.log(headers); // I know that this log outputs the RESPONSE headers, I want to find out how to output the REQUEST headers }); } catch (error) { console.log(error); } }; getAccounts(); // function callLa biblioteca node-fetch sí no parece tener ninguna capacidad de depuración o registro integrada (al leer detenidamente la fuente en github). Sin embargo, está construido sobre la biblioteca http que tiene algunas capacidades de registro/depuración.
No le mostrará la solicitud saliente exacta, pero le mostrará todos los datos recopilados para la solicitud justo antes de que se construya en la solicitud http final. Por ejemplo, si establece NODE_DEBUG=http en su entorno antes de ejecutar su programa, puede obtener un resultado como este:
HTTP 20624: call onSocket 0 0 HTTP 20624: createConnection google.com:80: { protocol: 'http:', slashes: true, auth: null, host: 'google.com', port: 80, hostname: 'google.com', hash: null, search: null, query: null, pathname: '/', path: null, href: 'http://google.com/', method: 'GET', headers: [Object: null prototype] { 'Some-Header': [ 'someValue' ], Accept: [ '*/*' ], 'User-Agent': [ 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)' ], 'Accept-Encoding': [ 'gzip,deflate' ], Connection: [ 'close' ] }, agent: undefined, servername: 'google.com', _agentKey: 'google.com:80:' } HTTP 20624: sockets google.com:80: 1 1 HTTP 20624: outgoing message end. (node:20624) Warning: Setting the NODE_DEBUG environment variable to 'http' can expose sensitive data (such as passwords, tokens and authentication headers) in the resulting log. (Use `node --trace-warnings ...` to show where the warning was created) HTTP 20624: requestTimeout timer moved to req HTTP 20624: AGENT incoming response! HTTP 20624: call onSocket 0 0 HTTP 20624: createConnection www.google.com:80: { protocol: 'http:', slashes: true, auth: null, host: 'www.google.com', port: 80, hostname: 'www.google.com', hash: null, search: null, query: null, pathname: '/', path: null, href: 'http://www.google.com/', method: 'GET', headers: [Object: null prototype] { 'Some-Header': [ 'someValue' ], Accept: [ '*/*' ], 'User-Agent': [ 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)' ], 'Accept-Encoding': [ 'gzip,deflate' ], Connection: [ 'close' ] }, agent: undefined, servername: 'www.google.com', _agentKey: 'www.google.com:80:' } HTTP 20624: sockets www.google.com:80: 1 2 HTTP 20624: outgoing message end. HTTP 20624: CLIENT socket onClose HTTP 20624: removeSocket google.com:80: writable: false HTTP 20624: HTTP socket close HTTP 20624: requestTimeout timer moved to req HTTP 20624: AGENT incoming response! done HTTP 20624: AGENT socket.destroySoon() HTTP 20624: CLIENT socket onClose HTTP 20624: removeSocket www.google.com:80: writable: false HTTP 20624: HTTP socket closeY, si configuras:
NODE_DEBUG=http,net,streamObtendrá aún más información. Todavía no veo ninguna forma con esta depuración de obtener los datos exactos que se envían para la solicitud http, aunque los datos del módulo http muestran lo que se ensamblará en esa solicitud. Es posible que deba usar un proxy o un registrador de red para ver la transmisión exacta que se envía al servidor.