所以我有一个json字符串,我正在尝试发送到本地服务器。我用来发布它的代码是:
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();
}
然后我有一个运行express的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成功)
我假设我在这里做错了什么,但是什么?
答案 0 :(得分:1)
由于您要发布json
,因此您应该将json中间件用于body-parser
app.use(bodyParser.json());
答案 1 :(得分:1)
尝试使用bodyParser.json()
代替bodyParser.urlencoded()
。