如何在 Node.js 后端正确解析 React 前端传来的 JSON 数据

7次阅读

如何在 Node.js 后端正确解析 React 前端传来的 JSON 数据

本文详解如何在 express(或类似 node.js后端中正确提取前端通过 fetch 发送的 json 请求体中的目标字段(如合约地址),避免将整个对象误作字符串或未解构直接使用。

本文详解如何在 express(或类似 node.js后端中正确提取前端通过 fetch 发送的 json 请求体中的目标字段(如合约地址),避免将整个对象误作字符串或未解构直接使用。

在前后端分离开发中,react 前端常通过 fetch 向 node.js 后端发送结构化数据(如智能合约地址),而后端需精准提取该值以调用 web3 相关逻辑(例如 ethers.js 读取链上价格)。但初学者常因请求体解析不当,导致后端收到的是完整 JSON 对象而非原始字符串值——正如问题中所示:{ feed: ‘0xD4a338…’ },而非期望的纯地址字符串。

✅ 正确处理流程

1. 前端:确保发送格式规范(已正确)

你的前端代码是标准且合规的:

export async function getPrice() {   const { feed } = useStore.getState();    try {     const response = await fetch("/api/getPrice", {       method: "POST",       headers: {         "Content-Type": "application/json",       },       body: JSON.stringify({ feed }), // ✅ 发送 { feed: "0x..." }     });      const result = await response.json();     console.log("Backend response:", result);   } catch (error) {     console.error("Fetch error:", error);   } }

✅ 关键点:JSON.stringify({ feed }) 将地址封装为合法 JSON 对象,符合 REST API 最佳实践。

2. 后端:必须显式解析请求体并解构

Node.js 默认不会自动解析 JSON 请求体。若你使用 Express,需手动启用 express.json() 中间件;否则 req.body 将为空或为原始流。

立即学习前端免费学习笔记(深入)”;

✅ Express 示例(推荐)
// server.js 或路由文件 const express = require('express'); const app = express();  // ? 必须启用 JSON 解析中间件 app.use(express.json()); // 解析 application/json app.use(express.urlencoded({ extended: true })); // 可选:兼容表单提交  // 定义 /api/getPrice 路由 app.post('/api/getPrice', async (req, res) => {   try {     // ✅ 正确解构:req.body 是解析后的 JS 对象     const { feed } = req.body; // ← 核心!从 { feed: "0x..." } 中提取字符串值      // 验证非空 & 格式(防御性编程)     if (!feed || typeof feed !== 'string' || !/^0x[a-fA-F0-9]{40}$/.test(feed)) {       return res.status(400).json({ error: 'Invalid Ethereum address' });     }      console.log('Extracted feed address:', feed); // 输出:0xD4a33860578De61DBAbDc8BFdb98FD742fA7028e      // ✅ 此处可安全传入 ethers Contract 方法     // const price = await contract.getPrice(feed);      res.json({ success: true, address: feed, /* price */ });   } catch (err) {     console.error('Backend error:', err);     res.status(500).json({ error: 'Internal server error' });   } });

⚠️ 常见错误:直接把 req 当作函数参数(如 exports.getPrice = async (feed) => {…})——这是无效的。Node.js http 处理器接收的是 (req, res, next) 三元参数,feed 不会自动注入。

3. 其他框架适配提示

  • Next.js API Routes:req.body 已自动解析,直接 const { feed } = req.body 即可。
  • Fastify:需注册 fastify-json-body 插件或使用内置 schema 配置。
  • 原生 Node.js(无框架):需手动监听 data/end 事件拼接 Buffer 并 JSON.parse()。

? 调试技巧

  • 在后端入口加日志:console.log(‘Raw body:’, req.body, typeof req.body);
  • 使用 postman 测试接口,确认请求头含 Content-Type: application/json;
  • 检查 Express 版本:v4.16+ 才默认支持 express.json()。

✅ 总结

环节 正确做法 错误示例
前端 JSON.stringify({ feed }) + Content-Type: application/json 漏设 headers 或用 FormData 发送 JSON
后端中间件 app.use(express.json()) 忘记启用,导致 req.body === {}
数据提取 const { feed } = req.body 直接 console.log(req.body) 误以为 feed 是字符串

只要确保后端正确解析并解构请求体,你就能稳定获取到纯净的合约地址字符串,无缝对接 ethers.Contract 等链上操作。

text=ZqhQzanResources