2014-06-06 99 views
0

我正在向java中的節點服務器發送json對象。我想顯示服務器控制檯中的值。在服務器控制檯上,我得到未定義的如何獲取JSON對象並使用express在nodejs中解析它。使用快遞在節點服務器上接收JSON對象

Java代碼的

 try 
      { 
       HttpClient client = new DefaultHttpClient(); 
       HttpPost post = new HttpPost("http://example.com:3000/"); 
       JSONObject msg = new JSONObject(); Log.e("data",code); 
       msg.put("data", code); 
       HttpEntity entity = new StringEntity(msg.toString()); 
       BufferedReader reader = new BufferedReader(new 
       InputStreamReader(client.execute(post).getEntity().getContent())); 
       String response = reader.readLine(); 
       Log.e("response", response); 

      } 
      catch(Exception e) 
      { Log.e("",e.toString()); 
      } 

節點服務器

var express = require("express"); 
var http=require("http"); 
var app = express(); 
app.use(express.bodyParser()); 
app.post("/", function(request, response) 
{ 


    response.send(JSON.stringify({success: true})); 
    var token = request.body.data; 
    console.log(token); 


}); 
app.listen(3000); 
+1

您似乎沒有將'msg'或'entity'附加到'post'請求或'client'。 –

+0

可以糾正它喬納森? –

+0

我hv糾正它..!無論如何感謝喬納森指出它..!就在我發佈我的查詢後,我意識到它。 –

回答

1

您忘記將實體附加到您的發佈請求。

try 
     { 
      HttpClient client = new DefaultHttpClient(); 
      HttpPost post = new HttpPost("http://example.com:3000/"); 
      JSONObject msg = new JSONObject(); Log.e("data",code); 
      msg.put("data", code); 

      // modified code below 
      HttpEntity entity = new StringEntity(msg.toString(), ContentType.create("application/json")); 
      post.setEntity(entity); 

      BufferedReader reader = new BufferedReader(new 
      InputStreamReader(client.execute(post).getEntity().getContent())); 
      String response = reader.readLine(); 
      Log.e("response", response); 

     } 
     catch(Exception e) 
     { Log.e("",e.toString()); 
     } 
+0

是的..!我剛剛意識到這一點。無論如何感謝很多..! :) –

1

您是否嘗試過使用:

var bodyParser = require('body-parser'); 
app.use(bodyParser.json()); 

這需要你安裝body-parser packag e:

$ npm install body-parser