如何在Node.js(NestJS)应用中查看 outgoing HTTP 请求
查看NestJS应用中node-fetch发起的所有请求方案
一、Node.js全局拦截方案
直接重写node-fetch的全局方法,在请求发送和响应返回时打印详细信息,无需改动业务代码:
创建日志拦截文件src/utils/fetch-logger.js:
const originalFetch = require('node-fetch'); global.fetch = async (...args) => { const [url, options = {}] = args; // 打印请求详情 console.log(`[REQUEST] ${options.method || 'GET'} ${url}`); console.log('Headers:', options.headers); options.body && console.log('Body:', options.body); const response = await originalFetch(...args); // 打印响应详情 console.log(`[RESPONSE] ${response.status} ${url}`); console.log('Response Headers:', response.headers.raw()); // 克隆响应流避免影响原业务逻辑 const clonedResponse = response.clone(); const body = await clonedResponse.text(); console.log('Response Body:', body); return response; };
在NestJS入口文件main.ts最顶部引入该文件:
require('./utils/fetch-logger');
启动应用后,所有node-fetch发起的请求都会在控制台输出完整日志。
二、NestJS服务封装方案
如果希望更规范地管理请求,封装统一的Fetch服务,将日志逻辑内置:
创建src/fetch/fetch.service.ts:
import { Injectable } from '@nestjs/common'; import fetch from 'node-fetch'; @Injectable() export class FetchService { async request(url: string, options?: RequestInit) { // 输出请求日志 console.log(`[FETCH REQUEST] ${options?.method || 'GET'} ${url}`); console.log('Request Headers:', options?.headers); options?.body && console.log('Request Body:', options?.body); const response = await fetch(url, options); // 输出响应日志 console.log(`[FETCH RESPONSE] ${response.status} ${url}`); console.log('Response Headers:', response.headers.raw()); const clonedResponse = response.clone(); const body = await clonedResponse.text(); console.log('Response Body:', body); return response; } }
在业务模块中注入该服务,用fetchService.request()代替直接调用node-fetch,即可统一管控请求日志。
三、代理工具抓包方案
如果需要类似浏览器控制台的可视化界面,可使用Charles、Mitmproxy这类代理工具抓包:
- 启动代理工具(比如Charles默认端口为8888)
- 设置Node.js的代理环境变量:
# Linux/macOS终端 export HTTP_PROXY=http://localhost:8888 export HTTPS_PROXY=http://localhost:8888 # Windows CMD set HTTP_PROXY=http://localhost:8888 set HTTPS_PROXY=http://localhost:8888 # Windows PowerShell $env:HTTP_PROXY="http://localhost:8888" $env:HTTPS_PROXY="http://localhost:8888" - 启动NestJS应用,所有
node-fetch的请求都会被代理工具捕获,可在工具界面查看请求头、请求体、响应状态、响应内容等完整信息,体验和浏览器控制台一致。
内容的提问来源于stack exchange,提问作者boumour ilyass
相关产品推荐
相关产品推荐

