Node.js跨服务器POST数据丢失求助:Server A向B传数据未被接收
解决Node.js中Server A通过Axios向Server B发送POST数据无法接收的问题
问题根源分析
Server A的Axios请求参数错误
Axios的post方法第二个参数直接对应请求体数据,不需要嵌套在data字段中;同时Axios会自动将JS对象序列化为JSON并设置Content-Type: application/json,手动调用JSON.stringify反而会导致数据格式异常。另外原代码中application\json的斜杠写法错误,应为application/json。Server B未正确处理POST请求体
Node.js原生http模块的req是可读流对象,POST数据以流式传输,直接打印req无法看到实际请求体,必须通过监听data和end事件来拼接完整数据。
修正后的Server A代码
var http = require('http') var axios = require('axios') const data = {name: 'karo', age: 18, email: 'karoakhgar82@hotmail.com'} http.createServer(function(req, res){ res.writeHead(200, {'Content-Type' : 'application/json'}) res.end(JSON.stringify(data)) }).listen(1337,'127.0.0.1') const api = axios.create({baseURL: 'http://127.0.0.1:1338'}) // 直接传递数据对象,Axios自动处理序列化与请求头 api.post('/', data) .then(res => { console.log('请求成功,响应内容:', res.data) }) .catch(error => { console.log('请求失败:', error) })
修正后的Server B代码
var http = require('http') http.createServer(function(req, res){ if (req.method === 'POST') { let requestBody = '' // 接收流式数据片段 req.on('data', chunk => { requestBody += chunk.toString() }) // 数据接收完成后处理 req.on('end', () => { console.log('原始POST数据:', requestBody) // 解析为JSON对象(可选) const parsedData = JSON.parse(requestBody) console.log('解析后的JSON数据:', parsedData) }) } res.writeHead(200, {'Content-Type' : 'text/plain'}) res.end('hello world') }).listen(1338,'127.0.0.1')
运行说明
先启动Server B,再启动Server A,即可在Server B的控制台看到接收的POST数据。若使用原生HTTP请求发送数据,同样需要正确设置Content-Type: application/json并发送序列化后的请求体,Server B端仍需通过流事件接收数据。
内容的提问来源于stack exchange,提问作者karoakhgar82
相关产品推荐
相关产品推荐

