Java发布JSON到本地服务器没有被Nodejs Express收到
所以我有一个jsonstring,我试图发送到本地服务器。 我用来发布它的代码是:
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服务器来监听这个post:
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"); })
我的问题是,服务器只是打印空的JSONstring(例如{}),而不是我发送的JSONstring。 (Java代码返回200成功)
我假设我在这里做错了什么,但是什么?
既然你发布了json
,你应该使用json中间件来进行body-parser
app.use(bodyParser.json());
尝试bodyParser.json()
而不是bodyParser.urlencoded()
。