2015-11-19 102 views
1

我正嘗試使用C#將數據發送到節點服務器。下面是代碼:無法使用C#將數據發佈到nodejs服務器HttpClient

節點+快遞:

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

這是請求對象的外觀: enter image description here

這是怎麼query and params如下: enter image description here

我缺少的東西?

+0

在你的app.post回調中,當你記錄請求時會發生什麼?你有看到身體對象嗎?如果不是,你在請求​​對象中看到了什麼? – Brant

+0

@Brant:查看更新的問題 – SharpCoder

+0

您對該請求的參數和查詢對象有什麼要求?從節點方面來說,我相信你的狀態良好。我認爲這是來自C#的POST請求的問題...我很想看看你試圖發送到主體中的數據是否被插入查詢obj中。 – Brant

回答

3

當您試圖訪問發佈到節點服務器的正文時,您需要使用正文分析器中間件。見下:

相關問題