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

C#向Node.js服务器发送POST请求时请求体为空的问题排查

问题分析与解决方案

核心错误点

你遇到的问题源于两个关键疏漏:

  1. C#端未指定请求体的Content-Type:仅设置Accept头是告诉服务器你接受JSON格式的响应,但没有告知服务器你发送的请求体是JSON类型,导致Node.js无法正确解析请求内容。
  2. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 04:06:04