2012-08-08 3 views
0

나는 반드시 내가 그걸 콘솔에서 모든 것을 작성하는 파이프를 사용하여 Node.js를구문 분석은

var http = require('http'); 
// Configure our HTTP server to respond with Hello World to all requests. 
var server = http.createServer(function (request, response) { 
console.log("Entering"); 


if (request.method === 'POST') { 

    // the body of the POST is JSON payload. 
    request.pipe(process.stdout); 
    } 

}); 

// Listen on port 8000, IP defaults to 127.0.0.1 
server.listen(8000); 

// Put a friendly message on the terminal 
console.log("Server running at http://127.0.0.1:8000/"); 

임에서이 자바 코드

DefaultHttpClient httpclient = new DefaultHttpClient();   
     HttpPost httpPostRequest = new HttpPost(URL);   
     StringEntity se;    
     se = new StringEntity(jsonObjSend.toString());   
     // Set HTTP parameters   
     httpPostRequest.setEntity(se);   
     httpPostRequest.setHeader("Accept", "application/json");    
     httpPostRequest.setHeader("Content-type", "application/json");   
     //httpPostRequest.setHeader("Accept-Encoding", "gzip"); 
     // only set this parameter if you would like to use gzip compression    
     long t = System.currentTimeMillis();    
     HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest); 

이 있습니다 데이터를 수신하십시오. 실제로 원하는 것은 JSON으로 데이터를 구문 분석 한 다음 배열에 저장하는 것입니다. 요청에서 데이터를 얻으려면 어떻게해야합니까? 코드 예제가있는 사람이 있습니까?

감사

답변

1
var http = require('http'); 
// Configure our HTTP server to respond with Hello World to all requests. 
var server = http.createServer(function (request, response) { 
console.log("Entering"); 


if (request.method === 'POST') { 

     // the body of the POST is JSON payload. 
     request.pipe(process.stdout); 

     var data = ''; 
     request.on('data', function(chunk) { 
      data += chunk; 
     }); 

     request.on('end', function() { 
      try { 
       data = JSON.parse(data); 
      } catch (e) { 
       console.log(e); 
      } 
     }); 
    } 

}); 

// Listen on port 8000, IP defaults to 127.0.0.1 
server.listen(8000); 

// Put a friendly message on the terminal 
console.log("Server running at http://127.0.0.1:8000/"); 
+0

덕분에 많은 다음과 같은 개념을 사용하는 (청크) .... "매개 변수 '데이터'의 의미 ... 어딘가에 정의되어 있습니까? – user1581164

+0

'데이터'및 '끝'은 이벤트 코드입니다.이 문서 http://nodejs.org/api/http를 확인하십시오. .html # http_event_data –

0

시도 내가 선 "request.on ('데이터', 함수에 대한 마지막 질문이 ... 코드에서

 response.on('data', function (chunk) 
     { 
       var data = chunk.toString(); 
       var data_val = JSON.parse(data) 
      }); 
관련 문제