2012-01-05 2 views
17

json 객체 데이터와 함께 C#에서 POST WebRequest를 보냅니다. 그리고이 같은 Node.js를 서버에 수신을 원하지 :Express node.js에서 JSON을받는 방법 POST 요청?

public string TestPOSTWebRequest(string url,object data) 
{ 
    try 
    { 
     string reponseData = string.Empty; 

     var webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest; 
     if (webRequest != null) 
     { 
      webRequest.Method = "POST"; 
      webRequest.ServicePoint.Expect100Continue = false; 
      webRequest.Timeout = 20000; 


      webRequest.ContentType = "application/json; charset=utf-8"; 
      DataContractJsonSerializer ser = new DataContractJsonSerializer(data.GetType()); 
      MemoryStream ms = new MemoryStream(); 
      ser.WriteObject(ms, data); 
      String json = Encoding.UTF8.GetString(ms.ToArray()); 
      StreamWriter writer = new StreamWriter(webRequest.GetRequestStream()); 
      writer.Write(json); 
     } 

     var resp = (HttpWebResponse)webRequest.GetResponse(); 
     Stream resStream = resp.GetResponseStream(); 
     StreamReader reader = new StreamReader(resStream); 
     reponseData = reader.ReadToEnd(); 

     return reponseData; 
    } 
    catch (Exception x) 
    { 
     throw x; 
    } 
} 

메소드 호출 :

TestPOSTWebRequest("http://localhost:3000/ReceiveJSON", new TestJSONType { a = 2, b = 3 }); 
또한
var express = require('express'); 
var app = express.createServer(); 

app.configure(function(){ 
    app.use(express.bodyParser()); 
}); 
app.post('/ReceiveJSON', function(req, res){ 
        //Suppose I sent this data: {"a":2,"b":3} 

           //Now how to extract this data from req here? 

           //console.log("req a:"+req.body.a);//outputs 'undefined' 
        //console.log("req body:"+req.body);//outputs '[object object]' 


    res.send("ok"); 
}); 

app.listen(3000); 
console.log('listening to http://localhost:3000');  

이, POST WebRequest 클래스의 C#을 종료는 다음과 같은 방법을 통해 호출

위 node.js 코드의 요청 개체에서 JSON 데이터를 구문 분석하려면 어떻게해야합니까?

답변

22

bodyParser은 편집console.log(req.body)

을, 당신을 위해 자동으로 해당 작업을 수행합니다 먼저 bodyParser 전에 app.router(), 그리고 다른 모든 것들을 포함하기 때문에 귀하의 코드가 잘못되었습니다. 그 나쁜. app.router()도 포함하면 안됩니다. Express는 자동으로 실행합니다.

var express = require('express'); 
var app = express.createServer(); 

app.configure(function(){ 
    app.use(express.bodyParser()); 
}); 

app.post('/ReceiveJSON', function(req, res){ 
    console.log(req.body); 
    res.send("ok"); 
}); 

app.listen(3000); 
console.log('listening to http://localhost:3000'); 

당신은 그 PARAMS와 POST 요청을 전송함으로써, Mikeal의 좋은 Request 모듈을 사용하여이를 테스트 할 수 있습니다 :

var request = require('request'); 
request.post({ 
    url: 'http://localhost:3000/ReceiveJSON', 
    headers: { 
    'Content-Type': 'application/json' 
    }, 
    body: JSON.stringify({ 
    a: 1, 
    b: 2, 
    c: 3 
    }) 
}, function(error, response, body){ 
    console.log(body); 
}); 

업데이트을 : 여기에 코드를 같이한다 방법 4 Express에 대한 body-parser를 사용 +. 콘텐츠 유형 :

+0

콘솔의 핵심으로 개체를 개막 .log (req.body)는 [object object]를 출력합니다. 나는 req.body.a도 시도했지만 정의되지 않은 내용을 인쇄합니다. – zee

+0

나는 내 코드를 편집 했으므로 다른 모든 미들웨어 (bodyParser 포함) 앞에 라우터가 놓여있었습니다. – alessioalex

+0

흠. 하지만 지금 console.log (req.body); outputs {}! json 객체 속성을 추출하는 방법 a & b? – zee

27

요청과 함께 보낼 수있다 "응용 프로그램/JSON; 문자셋 = UTF-8"

그렇지 않으면 bodyParser 다른 목적 :

+1

오 천재! 나는 그것을 어떻게 놓쳤는가! –

+1

선생님, 방금 저의 하루를 저축하셨습니다. – MetaLik