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

Node.js中使用客户端fetch()无法获取req.body的问题解决

无法读取req.body.content的原因与解决方案

问题场景

我在localhost:3000部署了一个Node.js应用app.js,代码如下:

app.js:

let http = require('http');

http.createServer((req, res) => {
    res.writeHead(200);
    let response;
    if(~req.url.indexOf('post')) {
        response = req.body.content;
    } else {
        response = '<script src="http://localhost/fetch.js"></script>';
    }
    res.end(response);
}).listen(3000);

fetch.js部署在另一台本地服务器,已成功加载到页面,代码如下:

fetch.js:

read('http://localhost:3000/?post').then((response) => {
    console.log(response);
});
async function read(url) {    
    const response = await fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json;charset=utf-8',
        },
        body: JSON.stringify({
            content: 'Text'
        })
    });
    return response.text();
}

运行node app.js后,页面触发POST请求时出现错误:

Can not read property 'content' of undefined


问题原因

Node.js原生http模块不会自动解析请求体,req对象本身并没有预设body属性,直接访问req.body.content自然会抛出未定义错误。HTTP请求的内容以流的方式传输,必须手动监听数据流事件来收集请求体数据,再根据请求头的Content-Type完成格式解析。


解决方案

修改app.js,手动处理请求体的接收与解析逻辑:

let http = require('http');

http.createServer((req, res) => {
    // 处理带post参数的POST请求
    if (~req.url.indexOf('post')) {
        let rawBody = '';
        // 监听数据流片段,拼接请求体内容
        req.on('data', chunk => {
            rawBody += chunk.toString();
        });
        // 数据流传输完成后,解析并返回结果
        req.on('end', () => {
            res.writeHead(200, { 'Content-Type': 'text/plain;charset=utf-8' });
            try {
                const parsedBody = JSON.parse(rawBody);
                res.end(parsedBody.content);
            } catch (err) {
                res.end('请求体JSON解析失败');
            }
        });
    } else {
        res.writeHead(200);
        res.end('<script src="http://localhost/fetch.js"></script>');
    }
}).listen(3000);

关键说明

  • 通过req.on('data')监听请求体的片段传输,逐步拼接完整内容
  • 在req.on('end')事件中完成JSON解析,此时请求体已完全接收
  • 增加try/catch捕获解析异常,避免格式错误导致服务崩溃
  • 给响应设置正确的Content-Type,保证返回内容编码正常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 06:22:03