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

使用Fetch发送POST请求,Express服务器无法正确解析请求体

问题:Fetch发送POST请求无法被Express正确解析为text属性

问题场景

客户端浏览器发送POST请求的代码:

const post = async (url, body) => {
    try {
        const response = await fetch(url, {
            method: `POST`,
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body
        });
        return response.json();
    } catch (error) {
        console.log(error.stack);
    }
}
const data = await post(`http://localhost:4050/analyze`, { text: "测试文本" });

Express服务器配置:

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

路由处理代码:

router.post(`/`, errorHandler(async (req, res, next) => {
    const { text } = req.body;
    console.log(req.body)

    const value = await analyze(text);

    res.json({ rephrased });
}));

控制台输出异常结果:

{ 'object Object': '' }

更新尝试:用JSON.stringify(body)处理请求体后,控制台输出变为:

{ '{"text":"asdfasdf"}': '' }

原因分析

你设置的Content-Type是application/x-www-form-urlencoded,这种格式要求请求体是键值对拼接的字符串(比如text=测试文本),但你直接传了JS对象,Fetch会自动把对象转成字符串[object Object],服务器解析后就会把这个字符串当作键,值为空,所以得到{ 'object Object': '' }。

后来用JSON.stringify把对象转成JSON字符串,本质还是字符串,不符合表单键值对格式,服务器会把整个JSON字符串当作键,值为空,所以出现{ '{"text":"asdfasdf"}': '' }的结果。

解决方法

方法1:将对象转为x-www-form-urlencoded格式的字符串

用URLSearchParams来处理请求体,它会自动把对象转换成符合要求的键值对字符串:

const post = async (url, body) => {
    try {
        const response = await fetch(url, {
            method: `POST`,
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams(body) // 用URLSearchParams处理对象
        });
        return response.json();
    } catch (error) {
        console.log(error.stack);
    }
}

方法2:改用JSON格式发送请求(更推荐)

如果不需要兼容旧系统,直接用JSON格式更简单:

  1. 客户端修改请求头和请求体:
const post = async (url, body) => {
    try {
        const response = await fetch(url, {
            method: `POST`,
            headers: {
                'Content-Type': 'application/json', // 修改为JSON类型
            },
            body: JSON.stringify(body) // 转成JSON字符串
        });
        return response.json();
    } catch (error) {
        console.log(error.stack);
    }
}
  1. 服务器添加JSON解析中间件:
// 保留原urlencoded中间件(若有其他表单请求需要),新增json中间件
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

这样服务器就能正确解析req.body,拿到text属性了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 00:05:19