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

Express后端POST请求req.body为undefined致JSON新增异常字段问题

Express投票应用中JSON文件出现undefined字段的问题及解决

我是JavaScript新手,正在开发一个Express后端应用,用于递增JSON文件中的投票数值。但每次通过键名递增对应值时,JSON文件中都会新增一个名为undefined的字段。

完整应用代码

const { response } = require("express");
const express = require("express");
const fs = require("fs").promises;
const path = require("path");

const app = express();

const dataFile = path.join(__dirname, "data.json");

//support POSTing form data wuth url encoded
app.use(express.json());


app.get("/poll", async (req, res) =>{
    //data is now the js object of the Json data json
    let data = JSON.parse(await fs.readFile(dataFile, "utf-8"));
    
    const totalVotes = Object.values(data).reduce((total, n) => total +=n, 0);
    
    data = Object.entries(data).map(([label, votes]) => {
        return{
            label,
            percentage: (((100 * votes) / totalVotes) || 0).toFixed(0) // or with 0 in the even that you divide by zero
        }
    });
    
    
    res.json(data);
    
});

app.use(express.urlencoded({ extended: true}));

app.post("/poll", async (req, res) => {
    const data = JSON.parse(await fs.readFile(dataFile, "utf-8"));

    data[req.body.add]++;

    await fs.writeFile(dataFile, JSON.stringify(data));
    
    res.json(data);
});
app.listen(3000, () => console.log("Server is running ..."));

POST前JSON文件内容

{
"JavaScript":0,
"TypScript":10,
"Both":3
}

问题现象

  • 使用Insomnia发送POST请求后,JSON文件新增undefined字段;第二次POST后该字段数值递增
  • 尝试添加请求体解析中间件无效,打印req.body显示为undefined

解决方法

最终定位到问题根源是Insomnia的请求格式错误:后端已经配置了express.json()和express.urlencoded({ extended: true})两种请求体解析中间件,但发送请求时必须选择对应的格式:

  • 如果请求体是JSON结构,需将Insomnia的请求格式设置为JSON
  • 如果是表单格式,需设置为Form URL Encoded

这样后端才能正确解析req.body,避免req.body.add为undefined,从而不再生成undefined字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 12:40:33