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

如何在Node.js中获取POST请求的Header与Body

获取POST请求的Header与Body实现方案

原生http模块中,请求对象req直接携带Header信息,而Body需要通过监听数据流事件收集解析,以下是基于你现有代码的修改方案:

1. 获取请求Header

请求的所有Header都存储在req.headers对象中,可直接访问指定字段或打印全部内容:

// 获取单个Header字段(字段名统一为小写)
const contentType = req.headers['content-type'];
// 打印所有请求Header
console.log('请求Header:', req.headers);

2. 收集并解析请求Body

POST请求的Body以流式传输,需通过data事件累积数据片段,end事件触发时处理完整数据,同时根据Content-Type解析对应格式:

修改后的完整服务器代码

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  // 仅处理POST请求
  if (req.method === 'POST') {
    // 1. 读取请求Header
    console.log('请求Header:', req.headers);
    const contentType = req.headers['content-type'];

    // 2. 收集请求Body数据
    let rawBody = '';
    req.on('data', chunk => {
      rawBody += chunk.toString(); // 将Buffer转换为字符串
    });

    req.on('end', () => {
      let parsedBody;
      try {
        // 根据Content-Type解析不同格式的Body
        if (contentType?.includes('application/json')) {
          parsedBody = JSON.parse(rawBody);
        } else if (contentType?.includes('application/x-www-form-urlencoded')) {
          // 解析表单格式数据
          parsedBody = Object.fromEntries(new URLSearchParams(rawBody));
        } else {
          // 其他格式直接保留原始字符串
          parsedBody = rawBody;
        }

        console.log('解析后的请求Body:', parsedBody);

        // 向客户端返回处理结果
        res.statusCode = 200;
        res.setHeader('Content-Type', 'application/json');
        res.end(JSON.stringify({
          message: 'POST请求处理完成',
          receivedHeaders: req.headers,
          receivedBody: parsedBody
        }));
      } catch (err) {
        // 处理解析错误
        res.statusCode = 400;
        res.setHeader('Content-Type', 'text/plain');
        res.end('Body解析失败:' + err.message);
      }
    });

    // 监听数据流错误
    req.on('error', err => {
      console.error('请求数据流错误:', err);
      res.statusCode = 500;
      res.end('服务器内部错误');
    });
  } else {
    // 非POST请求返回默认响应
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Hello World');
  }
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

测试方法

你可以用curl命令快速测试:

# 发送JSON格式POST请求
curl -X POST -H "Content-Type: application/json" -d '{"name":"demo","age":25}' http://127.0.0.1:3000

# 发送表单格式POST请求
curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d 'name=demo&age=25' http://127.0.0.1:3000

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 05:02:46