ノードフェッチリクエストをログに記録する方法はありますか? 質問する

ノードフェッチリクエストをログに記録する方法はありますか? 質問する

そこで私はnode.jsでいくつかのAPIを使用しようとしています。ノードフェッチサーバーに送信される最終リクエストをログに記録したいのですが、その方法が見つかりません。助けていただけませんか? コードは次のとおりです:

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 call

ベストアンサー1

ライブラリnode-fetch自体にはデバッグやログ記録の機能が組み込まれていないようです(起源httpただし、これは、ログ記録/デバッグ機能を備えたライブラリ上に構築されています。

正確な送信リクエストは表示されませんが、最終的な http リクエストに組み立てられる直前にリクエストに対して収集されたすべてのデータが表示されます。たとえば、NODE_DEBUG=httpプログラムを実行する前に環境を設定すると、次のような出力が得られます。

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 close

そして、次のように設定した場合:

NODE_DEBUG=http,net,stream

さらに多くの情報が得られます。このデバッグでは、http 要求に対して送信される正確なデータを取得する方法がまだわかりませんが、http モジュールのデータには、その要求に何が組み立てられるかが表示されます。サーバーに送信される正確なストリームを確認するには、プロキシまたはネットワーク ロガーのいずれかを使用する必要がある場合があります。

注: 2023年9月現在、nodejsの新しいバージョンではトレースイベントhttp などの一部のモジュールでは DEBUG フラグの代わりに使用されます。

おすすめ記事