如何实现Node.js查看 Vue3 项目请求日志

这是一个非常好的问题!在使用 Node.js 作为后端服务 (如 Express)来支持一个 Vue3 前端项目(通过 Vite 开发服务器运行)时,你可能会发现:

❓ "为什么我在 Express 后端看不到前端页面加载的请求日志?"

这是因为开发模式下,Vue3 项目由 Vite 独立运行在另一个端口上 (如 http://localhost:5173),而你的 Node.js 后端可能运行在 http://localhost:3000,它们是两个独立的服务。


🎯 目标

我们要实现:在 Node.js 后端查看浏览器对前端资源(HTML、JS、CSS)和 API 的完整请求日志


🧱 先理解:Vue3 开发模式的请求流程

less 复制代码
浏览器
  │
  ├─ 请求前端页面 ──→ Vite 服务器 (http://localhost:5173) ← 开发用
  │                       │
  │                       └── 提供 index.html、.js、.css 等
  │
  └─ 请求数据 ───────→ Node.js 后端 (http://localhost:3000) ← 你的 API
                          │
                          └── 返回 JSON 数据

👉 所以前端页面的请求 不会经过 Node.js 后端,你自然看不到这些日志。


✅ 解决方案一:让 Node.js 同时托管前端(推荐用于"一体化开发")

✅ 思路:

Node.js Express 服务器 不仅提供 API,还提供 Vue3 的静态文件(开发时通过代理,生产时 serve 构建结果)。

✅ 步骤:

1. 确保 Vue3 项目构建出静态文件

bash 复制代码
# 在 frontend 目录下构建
cd frontend
pnpm build
# 输出到 dist/ 目录

2. 在 Node.js 后端中托管静态文件

js 复制代码
// backend/server.mjs (ESM 模式)
import express from 'express';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';

const app = express();
const PORT = 3000;

// 获取 __dirname(ESM 中没有)
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

// 托管 Vue3 构建后的静态文件
app.use(express.static(join(__dirname, '../frontend/dist')));

// API 路由(你的数据接口)
app.get('/api/hello', (req, res) => {
  console.log('[API 请求] GET /api/hello 来自:', req.ip);
  res.json({ message: 'Hello from Node.js!' });
});

// 所有其他请求都返回 index.html(支持前端路由,如 Vue Router)
app.get('*', (req, res) => {
  console.log('[页面请求] GET', req.path, '来自:', req.ip);
  res.sendFile(join(__dirname, '../frontend/dist', 'index.html'));
});

app.listen(PORT, () => {
  console.log(`🚀 服务器运行在 http://localhost:${PORT}`);
});

3. 启动顺序

bash 复制代码
# 1. 构建前端
cd frontend
pnpm build

# 2. 启动后端(会自动 serve 静态文件)
cd ../backend
node server.mjs

4. 访问

打开 http://localhost:3000,所有请求(页面 + API)都会经过 Node.js,你就能在后端看到完整日志:

ini 复制代码
[页面请求] GET / 来自: ::1
[页面请求] GET /assets/index.abc123.js 来自: ::1
[API 请求] GET /api/hello 来自: ::1

✅ 解决方案二:开发时使用 Express 中间件代理 Vite(高级)

如果你不想每次构建 ,还想用 Vite 的热更新,可以用 Express 作为"网关",代理 Vite 开发服务器

✅ 思路:

scss 复制代码
浏览器 → Express (3000) → 代理到 Vite (5173) ← 热更新
               ↓
           API 路由

✅ 步骤:

1. 安装 http-proxy-middleware

bash 复制代码
cd backend
npm install http-proxy-middleware

2. 修改 server.mjs

js 复制代码
import express from 'express';
import { createProxyMiddleware } from 'http-proxy-middleware';
import { fileURLToPath } from 'url';
import { dirname } from 'path';

const app = express();
const PORT = 3000;
const __dirname = dirname(fileURLToPath(import.meta.url));

// 代理所有非 API 请求到 Vite 开发服务器
app.use(
  createProxyMiddleware({
    target: 'http://localhost:5173', // Vite 开发服务器
    changeOrigin: true,
    logLevel: 'debug', // 显示代理日志
    onProxyReq: (proxyReq, req, res) => {
      console.log('[代理请求] ', req.method, req.path);
    },
    onProxyRes: (proxyRes, req, res) => {
      console.log('[代理响应] ', req.method, req.path, '->', proxyRes.statusCode);
    },
  })
);

// 单独定义 API 路由(不被代理)
app.get('/api/hello', (req, res) => {
  console.log('[API 请求] GET /api/hello');
  res.json({ message: 'Hello from Node.js!' });
});

app.listen(PORT, () => {
  console.log(`🚀 Express 代理服务器运行在 http://localhost:${PORT}`);
  console.log(`👉 Vite 应在 http://localhost:5173 运行`);
});

3. 启动服务

bash 复制代码
# 终端 1:启动 Vite
cd frontend
pnpm dev

# 终端 2:启动 Express 代理
cd ../backend
node server.mjs

4. 访问 http://localhost:3000

  • 请求 / → 被代理到 Vite,你看到热更新
  • 请求 /api/hello → 被 Express 处理,你看到日志

✅ 解决方案三:使用 Vite 的 server.proxy(更常见)

更常见的做法是:让 Vite 代理 API 请求到 Node.js,而不是反过来。

js 复制代码
// frontend/vite.config.js
export default defineConfig({
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        changeOrigin: true,
        configure: (proxy, options) => {
          proxy.on('proxyReq', (proxyReq, req, res) => {
            console.log('[Vite 代理] API 请求:', req.method, req.url);
          });
        },
      },
    },
  },
});

这样你在 Vite 控制台能看到 API 请求日志,Node.js 也能收到请求并打印自己的日志。


✅ 如何在后端打印详细请求日志?

无论哪种方案,你都可以在 Express 中添加日志中间件:

js 复制代码
// 日志中间件
app.use((req, res, next) => {
  console.log(
    '[请求]', 
    new Date().toISOString(),
    req.method, 
    req.path, 
    '来自:', 
    req.ip,
    'UA:', 
    req.get('User-Agent')?.substring(0, 50)
  );
  next();
});

✅ 总结:如何选择?

场景 推荐方案
想看完整请求日志 + 一体化部署 ✅ 方案一:Node.js 托管构建后的 dist
开发时想用热更新 + 看日志 ✅ 方案二:Express 代理 Vite
标准开发流程 ✅ 方案三:Vite 代理 API 到 Node.js(Node.js 打印 API 日志)

🎯 最佳实践建议

  1. 开发时:用 Vite + 代理 API 到 Node.js,Node.js 打印 API 日志
  2. 生产时 :构建 Vue3,让 Node.js 托管 dist 文件
  3. 调试时:在 Express 中添加日志中间件,记录所有请求
相关推荐
扑克中的黑桃A8 小时前
飞算JavaAI家庭记账系统:从收支记录到财务分析的全流程管理方案
前端
我的写法有点潮8 小时前
IOS下H5 index层级混乱
前端·vue.js
一枚前端小能手8 小时前
🔥 闭包又把我坑了!这5个隐藏陷阱,90%的前端都中过招
前端·javascript
纯JS甘特图_MZGantt8 小时前
让你的甘特图"活"起来!mzgantt事件处理与数据同步实战指南
前端·javascript
鹏程十八少8 小时前
7. Android <卡顿七>优化动画导致卡顿:一套基于 Matrix 监控、Systrace/Perfetto 标准化排查流程(卡顿实战)
前端
8 小时前
中级前端进阶方向 第一步)JavaScript 微任务 / 宏任务机制
前端
小宋搬砖第一名8 小时前
深入剖析 Webpack AsyncQueue 源码:异步任务调度的核心
前端·webpack
JarvanMo8 小时前
Flutter 的 Hero Widget 有一个隐藏的超能力(大多数开发者从未使用过)
前端
WindrunnerMax8 小时前
从零实现富文本编辑器#7-基于组合事件的半受控输入模式
前端·前端框架·github