Ratpack 无法从 body 检索值

Ratpack unable to retrieve value from body

我正在通过 post 请求从网页向服务器发送数据。

$("#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 }));
            });

借助此 java 脚本。我确定它已发送到服务器并到达那里。

在服务器上,我尝试检索写入数据的值。

.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");
                    })

不幸的是,我没有找到任何如何相应地检索字符串值的指南。

我尝试了上面的方法,但这确实永远卡在了 ExecHarness 中。

我想获取这些值。带他们做一个新的javaobject然后用另一个javaobject的json回应。 (第二个object取决于之前的object数据)

Ratpack's API reference 而不是 ExecHarness 尝试这样的事情:

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"); 
})

你也可以链接它,例如

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());
 })