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

Fetch发送POST请求时服务端request.body.value为undefined的问题咨询

问题原因

  • 前端请求体格式不符合预期:直接将数字15作为请求体发送,没有封装为带value属性的JSON对象,也未指定JSON格式对应的请求头,服务端无法识别到value字段。
  • 服务端缺少JSON格式解析能力:当前仅配置了express.urlencoded()中间件,该中间件仅支持解析application/x-www-form-urlencoded格式的表单请求,无法处理JSON格式的请求体。你此前传JSON参数的功能正常,是因为对应请求同时满足了前端传标准JSON结构、加了正确请求头、后端有对应解析中间件的条件。

修复方案

后端调整:新增JSON解析中间件

在Express全局配置中添加express.json(),用于解析JSON格式的请求体:

// 新增JSON解析中间件
app.use(express.json());
app.use(express.urlencoded({
    extended: true
}));  
app.post('/async', (request, response) => {
    const size = request.body;
    console.log(size.value)
    let data = [];
    for (let i = 0; i < size.value; i++) {
        data.push(faker.fake("{{name.lastName}}" + " " + "{{name.firstName}}"))
    }
    response.send(JSON.stringify(data))
})

前端调整:规范fetch请求参数

将参数封装为带value属性的JSON对象后序列化,同时指定Content-Type请求头标识为JSON格式:

async function sendAsync(event) {
    event.preventDefault();
    let value = 15;
    let response = await fetch('/async', {
        method: "post",
        // 封装为符合要求的JSON结构并序列化
        body: JSON.stringify({value: value}),
        // 新增请求头声明请求体格式
        headers: {
            'Content-Type': 'application/json'
        }
    });
    if (!response.ok) throw new Error(response.statusText);
    let name = await response.json();
    displayUserInfo(name);
}

内容的提问来源于stack exchange,提问作者Thorben C.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 15:24:04