2015-10-21 35 views
2

所以我有一個json字符串,我試圖發送到本地服務器。我使用它張貼的代碼是:Java發佈JSON到本地服務器沒有被Nodejs Express收到

HttpClient httpClient = HttpClientBuilder.create().build(); //Use this instead 

try { 
    HttpPost request = new HttpPost("http://localhost:13000"); 
    StringEntity params =new StringEntity(jsonCont.toString()); 
    request.addHeader("content-type", "application/json"); 
    request.setEntity(params); 
    HttpResponse response = httpClient.execute(request); 
    System.out.println(response.getStatusLine()); 
}catch (Exception ex) { 
    // handle exception here 
} finally { 
    httpClient.getConnectionManager().shutdown(); 
} 

然後,我有一個服務器的NodeJS運行快速監聽崗位:

var express = require('express'); 

var bodyParser = require("body-parser"); 

var app = express(); 

app.use(bodyParser.urlencoded({ 
    extended: false 
})); 

app.post('*', function (request, response) { 
    console.log(request); 
    response.send("200"); 
}); 

app.listen(13000, function() { 
    console.log("Started on PORT 13000"); 
}) 

我的問題是,服務器只是打印空json字符串(例如{}),而不是我發送的json字符串。 (Java代碼返回200成功)

我假設我在這裏做錯了什麼,但什麼?

回答

1

既然你發佈json,你應該使用JSON中間件身體解析器

app.use(bodyParser.json()); 
1

嘗試bodyParser.json(),而不是bodyParser.urlencoded()