简体   繁体   中英

Ratpack unable to retrieve value from body

I'm sending data via post request from the webpage to the server.

$("#1, #2, #3, #4").on("click", function(){
            console.log($(this).attr("id"));
              var xhr = new XMLHttpRequest();
              xhr.open("POST", "SimpleServlet.html", true);
              xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
              xhr.send(JSON.stringify({"product_id": $(this).attr("id"), "quantity" : 1 }));
            });

With the help of this javascript. I am sure that it gets sent to the server and it arrives there.

On the server I try to retrieve the values I wrote to the data.

.post("SimpleServlet.html", ctx ->
                    {
                        final Response response = ctx.getResponse();

                        System.out.println("Getting result");

                        final ExecResult<String> result = ExecHarness.yieldSingle(c ->
                                ctx.parse(String.class));


                        System.out.println("Getting value");
                        response.send("webshop.html");
                    })

I, unfortunately, didn't find any guide how to retrieve the String values accordingly.

I tried the above but this does get stuck inside the ExecHarness forever.

I would like get receive the values. Take them to make a new java object and then respond with the json of another java object back. (Second object depends on previous object data)

Ratpack's API reference Instead of ExecHarness try something like this:

ctx.getRequest().getBody().then({ data ->
  String text = data.getText();
  // parse text with whatever you use, e.g. Jackson

  System.out.println("Getting value");
  response.send("webshop.html"); 
})

You can chain it too, eg

context.getRequest().getBody().flatMap({ data ->
    //parse data and get id
    //call to async service who returns Promise
    return service.getReport(id).map((String report) -> {
        // do some staff
    })
 }).then({
     //final staff before send response
     //import static ratpack.jackson.Jackson.json; 
     context.getResponse().send(json(result).toString());
 })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM