You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Express POST请求无法获取请求体内容问题求助

问题解决:Express后端无法获取FormData请求体

问题原因

前端通过FormData发送的请求,请求头Content-Type为multipart/form-data,而你使用的express.json()中间件仅能解析application/json格式的请求体,因此后端无法正确解析req.body,导致控制台打印空对象。

解决方案:使用multer中间件解析FormData

multer是Express官方推荐的multipart/form-data处理中间件,具体步骤如下:

1. 安装multer

npm install multer

2. 修改后端代码,引入并配置multer

const express = require('express');
const multer = require('multer');
const app = express();

// 配置内存存储(适合仅传递表单字段、无文件上传的场景)
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });

// 路由中使用upload.none()解析纯表单字段
app.post("/notes/create", upload.none(), (req, res) => {
  console.log(req.body); // 现在可正常获取{ desc: 'xxx' }格式的请求体
  res.json(req.body);
});

app.listen(5000, () => console.log('Server running on port 5000'));

3. 修复前端代码的小问题

前端fetch回调中result未定义,需先解析响应内容:

const handleClick = () => {
  const fd = new FormData();
  fd.append("desc", value);
  fetch("http://localhost:5000/notes/create", {
    method: "POST",
    body: fd,
  }).then((res) => res.json()) // 先将响应解析为JSON格式
    .then((result) => {
      alert(JSON.stringify(result)); // 正确展示返回结果
    }).catch(err => console.error(err)); // 建议添加错误捕获逻辑
};

补充说明

  • 若后续需要上传文件,只需调整multer的存储配置(比如改为磁盘存储),并使用upload.single('file')或upload.array('files')等对应方法。
  • 避免在同一路由同时使用express.json()和multer,防止解析逻辑冲突。

内容的提问来源于stack exchange,提问作者shark_feeder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 21:12:49