C#向Node.js服务器发送POST请求时请求体为空的问题排查
问题分析与解决方案
核心错误点
你遇到的问题源于两个关键疏漏:
- C#端未指定请求体的Content-Type:仅设置
Accept头是告诉服务器你接受JSON格式的响应,但没有告知服务器你发送的请求体是JSON类型,导致Node.js无法正确解析请求内容。 - Node.js端未配置JSON解析中间件:如果使用Express框架,默认不会自动解析JSON请求体,必须手动添加中间件才能让
req.body获取到内容。
修正后的C#代码
修改StringContent的创建方式,明确指定编码和Content-Type为application/json:
using System.Net.Http; using System.Text; using Newtonsoft.Json; using System.Net.Http.Headers; public static async Task<string> GetCred() { var values = new Dictionary<string, string> { { "test1", "1" }, { "test2", "2" } }; var json = JsonConvert.SerializeObject(values, Formatting.Indented); // 关键:指定Content-Type为application/json var stringContent = new StringContent(json, Encoding.UTF8, "application/json"); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var response = await client.PostAsync("http://publicIp:port/api/server", stringContent); var responseString = await response.Content.ReadAsStringAsync(); return responseString; }
修正后的Node.js代码(以Express为例)
确保在路由注册前添加express.json()中间件,用于解析JSON请求体:
const express = require('express'); const app = express(); // 关键:添加JSON解析中间件 app.use(express.json()); const server = async (req, res) => { // 现在能正常打印请求体内容 console.log(req.body); res.send('请求已处理'); }; app.post('/api/server', server); app.listen(port, () => { console.log(`服务器运行在端口 ${port}`); });
内容的提问来源于stack exchange,提问作者seriously
相关产品推荐
相关产品推荐

