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

Node.js纯http模块跨服务器POST数据接收异常问题求助

问题解决:纯Node.js http模块实现服务器间POST数据传输

问题根源分析

  1. 请求方法错误:服务器A的请求配置里method设为了GET,但GET请求不支持请求体,导致服务器B无法接收到数据,必须改为POST。
  2. 缺少必要请求头:发送JSON格式的POST数据时,需要告知服务器数据类型,同时指定数据长度,否则服务器无法正确解析请求体。
  3. 服务器B未处理请求体:POST数据是流式传输的,不能直接通过打印req对象获取,需要监听data和end事件拼接完整数据。

修正后的服务器A代码

var http = require('http')

const data = {name: 'karo', age: 18, email: 'helloworld@gmail.com'}
// 服务器A自身的HTTP服务(与向B发请求无关,仅示例)
http.createServer(function(req, res){
    // 修正Content-Type的斜杠(反斜杠改为正斜杠)
    res.writeHead(200, {'Content-Type': 'application/json'})
    res.end(JSON.stringify(data))
}).listen(1337,'127.0.0.1')

const postData = JSON.stringify(data)
const options = {
    protocol: "http:",
    hostname: "127.0.0.1", 
    port: "1338" ,
    path: "/", 
    method: "POST", // 改为POST方法
    headers: {
        'Content-Type': 'application/json',
        'Content-Length': Buffer.byteLength(postData) // 计算数据字节长度
    }
};
     
// 发送POST请求
var post_req = http.request(options, function(res) {
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        console.log('Response from B: ' + chunk);
    });
})
// 处理请求发送错误
post_req.on('error', (err) => {
    console.error('Request error:', err.message);
})
post_req.write(postData) 
post_req.end()

修正后的服务器B代码

var http = require('http')

http.createServer((req, res) => {
    if (req.method === 'POST') {
        let body = ''
        // 监听数据片段
        req.on('data', (chunk) => {
            body += chunk
        })
        // 数据接收完成
        req.on('end', () => {
            try {
                const data = JSON.parse(body)
                console.log('Received data from A:', data)
                // 给A返回响应
                res.writeHead(200, {'Content-Type': 'application/json'})
                res.end(JSON.stringify({status: 'success', message: 'Data received'}))
            } catch (err) {
                console.error('Parse data error:', err.message)
                res.writeHead(400, {'Content-Type': 'application/json'})
                res.end(JSON.stringify({status: 'error', message: 'Invalid JSON'}))
            }
        })
    } else {
        res.writeHead(405, {'Content-Type': 'application/json'})
        res.end(JSON.stringify({status: 'error', message: 'Method not allowed'}))
    }
}).listen(1338,'127.0.0.1')

运行步骤

  1. 先启动服务器B:node serverB.js
  2. 再启动服务器A:node serverA.js
  3. 查看服务器B的控制台,即可看到从A发送过来的JSON数据;服务器A的控制台会收到B返回的响应信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 19:01:27