简体   繁体   中英

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. 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)

 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.

So for some reason the POST body seems not to be received correctly.

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.

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];

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