Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vertx get body of a simple post reques

Tags:

java

vert.x

Their doc on vertx website isn't quite clear on how to receive the body of a request.

var vertx = Vertx.vertx();
var server = vertx.createHttpServer();
var Router = require("vertx-web-js/router");
var BodyHandler = require("vertx-web-js/body_handler");


var router = Router.router(vertx);


router.route().handler(BodyHandler.create().handle);

router.route('POST', "/a").handler(function (routingContext) {
  var response = routingContext.response();
  response.setChunked(true);
  response.write("a json received");
  var str = routingContext.getBodyAsJson()
  console.log(str);
  // Now end the response
  routingContext.response().end();
});

I get the error:

 vertx-js/util/console.js:9 ReferenceError: "inspect" is not defined

How am I supposed to know what to call if they don't even put it in their doc..

like image 419
Ced Avatar asked Feb 11 '17 14:02

Ced


2 Answers

Paulo said my version of vertx was outdated and this was a bug. I'll take his word for it. In the meantime I tried doing it in Java like in the answer I got. However I had more success doing it like this:

   router.route().handler(BodyHandler.create());


   router.route(HttpMethod.POST, "/iamonline").handler(rc -> {
        JsonObject json = rc.getBodyAsJson();
        System.out.println(json.getString("id"));
        HttpServerResponse response = rc.response();
        response.putHeader("content-type", "application/json");

        // Write to the response and end it
        response.end("{\"status\": 200}");
    });
like image 128
Ced Avatar answered Oct 08 '22 21:10

Ced


I ran into the same the first time. Use the .bodyHandler which is a convenience method for receiving the entire request body in one piece.

As a reference, I'll give you an example in Java (you can easily "transform" it into ECMAScript):

public void login(final RoutingContext routingContext) {
  routingContext.request().bodyHandler(bodyHandler -> {
    final JsonObject body = bodyHandler.toJsonObject();
    // `body` now contains you what you POST'ed
  });
}
like image 36
x80486 Avatar answered Oct 08 '22 21:10

x80486