简体   繁体   English

无法使用Play Framework从Ajax请求接收POST正文

[英]Unable to receive POST body from Ajax request using Play Framework

I am trying to send a POST request to my backend with some JSON data. 我正在尝试将一些JSON数据发送到POST请求到后端。 The call from the frontend looks like this: 来自前端的呼叫如下所示:

function register() {
  var user = $("#form_reg_username").val();
  var pass = $("#form_reg_password").val();
  var referal = $("#form_reg_referal").val();
  var postbody = {};
  var url = "http://" + location.host + "/api/admin/register";
  postbody.username = user;
  postbody.password = pass;
  postbody.referal = referal;

  var jsonbody = JSON.stringify(postbody);
  console.log(jsonbody);

  $.ajax({
    type: "POST",
    url: url,
    data: jsonbody,
    dataType: "json",
    success: registerHandler()
  });
}

The generated log looks like this: 生成的日志如下所示:

{"username":"jakob","password":"11111","referal":"urgotislove"}

Which is fine. 没关系

Here is the start of how I handle the request on the backend (I am using play 2.4) 这是我如何在后端处理请求的开始(我正在使用播放2.4)

 public Result adminRegister() {
        // Generate JSON from postbody
        ObjectNode json = Json.newObject();

        Logger.info("Body: " + request().body().asText());
        JsonNode body = request().body().asJson();

        String username = body.get("username").asText();
        String password = body.get("password").asText();
        String referal = body.get("referal").asText();
        ...
}

Looking at my application log the Info log looks like this: 查看我的应用程序日志,信息日志如下所示:

[info] application - Body: null

I am then getting a Nullpointer Exception in first line of trying to get the json values. 然后,在尝试获取json值的第一行中,我得到了Nullpointer异常。

So for some reason the POST body seems not to be received correctly. 因此,出于某种原因,似乎无法正确接收POST正文。

Thanks for any help in advance. 感谢您的任何帮助。

Turns out the Postbody was transferred correctly but for some reason the .asText() as well as the .asJson() method, did not work correctly and returned null. 事实证明Postbody已正确传输,但是由于某种原因.asText()以及.asJson()方法无法正常工作并返回null。

I fixed my issue with this little workaround: 我通过以下解决方法解决了问题:

Http.RequestBody requestBody = request().body();
Map<String, String[]> body = requestBody.asFormUrlEncoded();

String username = body.get("username")[0];
String password = body.get("password")[0];
String referal = body.get("referal")[0];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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