I am currently attempting to send a POST request to my backend using JSON data. The frontend call appears 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 resulting log is as follows:
{"username":"jakob","password":"11111","referal":"urgotislove"}
Everything seems fine at this point.
This is how I begin handling the request on the backend (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();
...
}
Upon checking my application's logs, the Info log displays:
[info] application - Body: null
Subsequently, a Nullpointer Exception occurs when trying to retrieve the json values.
It appears that the POST body is not being received correctly for some reason.
Any assistance on this matter would be greatly appreciated.