无法使用 C# HttpClient post 数据到 nodejs 服务器

Unable to post data to nodejs server using C# HttpClient

我正在尝试使用 C# 将数据发送到节点服务器。这是代码:

节点+快递:

var host = "127.0.0.1";
var port = 1337;
var express = require("express");
var app = express();

app.get("/", function(request, response){ //root dir
    response.send("Hello!!");
});

app.post("/build", function(request, response){ //root dir

    response.send("This is the post method");
});

app.listen(port, host);

C# 端:

using System.Net.Http;

            const string urlTemplate = "http://localhost:1337/build";
            var userQuery = new User();
            userQuery.Name = "Test";
            userQuery.Location= "Test Location";
            userQuery.Age= 26;

            var client = new HttpClient();
            client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json; charset=utf-8");
            client.Timeout = TimeSpan.FromMilliseconds(600000);
            var task = client.PostAsJsonAsync(urlTemplate, userQuery);
            var result = task.Result.Content.ReadAsStringAsync().Result;

我能够从服务器获得响应。但是当我尝试说 request.body 来获取 posted 信息时,request.body is undefined.

这是请求对象的样子:

这是 query and params 的样子:

我是不是漏掉了什么?

当您尝试访问发布到节点服务器的正文时,您需要为此使用 body-parser 中间件。见下文:

var express = require('express')
var bodyParser = require('body-parser')

var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())