Nodejs Express未接收到Java向本地服务器发送JSON
所以我有一个json字符串,我正试图发送到本地服务器。我用来发布它的代码是:Nodejs Express未接收到Java向本地服务器发送JSON,java,json,node.js,express,Java,Json,Node.js,Express,所以我有一个json字符串,我正试图发送到本地服务器。我用来发布它的代码是: HttpClient httpClient = HttpClientBuilder.create().build(); //Use this instead try { HttpPost request = new HttpPost("http://localhost:13000"); StringEntity params =new StringEntity(jsonCont.toString()
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成功)
我假设我在这里做错了什么,但是什么呢?既然您发布了
json
,那么您应该使用json中间件作为主体解析器
app.use(bodyParser.json());
尝试bodyParser.json()
而不是bodyParser.urlencoded()