目录

前端-向后端传数据,判断问题所在的调试过程

前端 | 向后端传数据,判断问题所在的调试过程


理清架构:

vue文件中(界面)—— 调用

函数

js文件中(api交互)—— 定义

函数,并向后端 发送 post 请求

node后端中(处理)—— 接收 post 请求

,并进行 处理


1. 在 vue 文件中,在调用函数之前 先打印传入的数据

ChatView.vue 里调用 saveToFile 之前,先打印要传入的 userMessage 的数据格式:

const sendMessage = async () => {
  
  console.log("调用 saveToFile 之前,用户输入:", userMessage); // 查看传入的数据格式

  await saveToFile(userMessage); // 调用保存函数
}

要求:调用的传入的数据是


2. 在 js 文件中,打印接收到的数据

修改 deepseek.js ,在 saveToFile() 里,先打印 text 的内容以及类型 用于判断接受到的数据:

export const saveToFile = async (text) => {
  console.log("deepseek.js 收到的 text:", text); // 确保数据传递正确
  console.log("text 的类型:", typeof text); // 确保是字符串

  try {
    const response = await fetch("http://localhost:3000/save", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ content: text }), // 发送 JSON 格式数据
    });

    console.log("请求返回 response:", response); // 查看请求结果

    if (!response.ok) {
      throw new Error("服务器返回错误:" + response.status);
    }

    console.log("保存成功");
  } catch (error) {
    console.error("存档失败:", error);
  }
};

🚀 作用

  • 确保 text 的数据格式正确。
  • console.log("text 的类型:", typeof text); 确保 text 是字符串
  • console.log("请求返回 response:", response); 查看 fetch 请求是否成功。

若发现 text 的格式是 content: Proxy ,则在console.log之前添加:

// 解析contentArray为文本格式 ——> 把响应式数据 ref([])即Proxy 转为普通数组

    const normalArray = JSON.parse(JSON.stringify(contentArray.value || contentArray));
    const text = JSON.stringify({ content: normalArray });

用途:

把响应式数据 ref([])即Proxy,转为普通数组 。这样才可以进行解析。

代码如图:

https://i-blog.csdnimg.cn/direct/26ac095242f44471bef04b81749a139d.png

知识点:

JSON.stringify() —— 对象→json字符串

JSON.parse() —— json字符串→js对象


3. 在浏览器 Network 面板查看请求数据

  1. 打开 浏览器开发者工具(F12 或 Ctrl+Shift+I)
  2. 切换到 Network(网络) 面板
  3. 找到 save 请求,点击后查看:
    • Headers(请求头) → 确保

      Content-Type: application/json

    • Request Payload(请求数据) → 确保 body

      里是 { "content": "你的数据" }


4. 在 server.js 中查看请求数据

修改 server.js ,在 POST /save 里打印收到的数据:

const express = require("express");
const cors = require("cors");
const fs = require("fs");

const app = express();
app.use(cors());
app.use(express.json()); // 确保能解析 JSON 数据

app.post("/save", (req, res) => {
  console.log("后端接收到的数据:", req.body); // 打印请求内容

  const content = req.body.content;
  console.log("格式化后的 content:", content); // 确保是字符串

  fs.appendFile("conversation.txt", content + "\n", (err) => {
    if (err) {
      console.error("写入文件失败:", err);
      return res.status(500).json({ error: "写入失败" });
    }
    res.json({ message: "写入成功" });
  });
});

app.listen(3000, () => {
  console.log("服务器运行在 http://localhost:3000");
});

🚀 作用

  • console.log( "后端接收到的数据: ", req.body) ; 确保前端传递的 JSON 格式正确。
  • console.log("格式化后的 content:", content) ; 确保 content 是字符串
  • fs.appendFilecontent 追加写入 conversation.txt ,每条信息换行存储。

5. 确保 JSON 格式正确

如果 deepseek.js(api交互的js)console.log("text 类型:", typeof text);

发现 text 不是字符串,你可以用:

const textString = JSON.stringify(text, null, 2);  // 格式化 JSON
console.log("格式化后的 text:", textString);

这样你可以更容易发现问题。

知识点: JSON.stringify(req.body, null, 2)

JSON.stringify(req.body)对象→json字符串

JSON.stringify(req.body, null, 2) 是一个常见的 JavaScript 代码片段,主要用于将对象 req.body 序列化为格式化的 JSON 字符串 ,便于人类阅读或调试。以下是详细解析:


1. 代码结构

JSON.stringify(value, replacer, space)
  • value
    要序列化的对象 (这里是 req.body ,通常来自 HTTP 请求的请求体,如 POST/PUT 请求的 JSON 数据)。
  • replacer
    可选参数,用于 过滤或转换 属性。此处设为 null ,表示不进行过滤或修改。
  • space
    可选参数,指定 缩进的空格数或字符串 。此处设为 2 ,表示用 2 个空格 缩进格式化输出。

2. 作用

核心功能
  • req.body (通常是 JavaScript 对象)转换为 格式化的 JSON 字符串

  • 例如,原始对象:

    { name: "Alice", age: 30, address: { city: "Shanghai" } }

    会被转换为:

    {
      "name": "Alice",
      "age": 30,
      "address": {
        "city": "Shanghai"
      }
    }
关键特点
  1. 美化输出 (Pretty-Print):

    • space: 2 会为 JSON 字符串添加换行和缩进(2 个空格),使数据结构更清晰。
    • 适合日志记录、调试输出或直接展示给用户。
  2. 保留完整数据 (不过滤):

    • replacer: null 表示不修改或过滤任何属性,所有可序列化的属性都会被保留。
  3. 兼容性 :

    • 自动处理 Dateundefined函数 等类型(遵循 JSON.stringify 的默认规则)。

3. 典型使用场景

(1) 日志记录

将请求体内容记录到日志文件或控制台,便于排查问题:

console.log(JSON.stringify(req.body, null, 2));
// 输出:
// {
//   "username": "alice",
//   "action": "login"
// }
(2) API 响应

向客户端返回格式化的 JSON 数据(如调试接口时):

res.send(JSON.stringify(req.body, null, 2));
(3) 存储数据

将请求体保存到文件或数据库(格式化的 JSON 更易维护):

fs.writeFileSync("request.json", JSON.stringify(req.body, null, 2));

例子——控制台的显示

https://i-blog.csdnimg.cn/direct/a944b6450ea4437b91010ea4fd5306f9.png


最终检查点

  • ChatView.vueconsole.log

    确保 saveToFile 传入正确的内容。

  • deepseek.js

    console.log

    确保 text

    是字符串 ,并打印 fetch 请求的 response

  • Network 面板

    → 检查请求 Headers

    Request Payload ,确保格式正确。

  • server.jsconsole.log

    确保后端收到的 JSON 正确 , fs.appendFile 成功写入文件。


✅ 这样,你就可以完整跟踪 Vue 组件、deepseek.js、fetch 请求、server.js 之间的数据流,并找到问题所在! 🚀

主要是通过 输出和检查network面板 进行调试,查看 控制台结果和node终端的结果 ,来修改代码,找到问题所在。