Issue with retrieving POST body from Ajax call in Play Framework

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.

Answer №1

It turns out that the Postbody was successfully transferred, but strangely enough, both the .asText() and .asJson() methods were not functioning properly and returned null.

To resolve this issue, I implemented a quick 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];

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to capture screenshot of hovered element using Cypress

Having an issue with taking a screenshot of an element with a hover effect. The screenshots always come out without the hover effect applied. tableListMaps.lineWithText('Hello world', 'myLine'); cy.get('@myLine').realH ...

"Implementing the jQuery draggable feature within sortable strips by assigning them

There is a function where users can drag text items from a 'library' into a list to create and edit their own document. Both lists are generated through an Ajax call. It is important to note that the receiving list is created before the donor lis ...

Can you provide a guide on setting up and utilizing mathlive within NuxtJS?

Can anyone assist me? I am trying to figure out why my code is not working or if I have implemented it incorrectly. I used npm i mathlive to obtain input. However, following the instructions for implementing nuxt plugins in the documentation has not yield ...

Attempting to run the npm install command led to encountering a SyntaxError with an

Recently, I made some alterations to my npm configuration and ever since then, I have been consistently encountering the same error whenever I try to install various packages. It seems that due to a personal mistake in changing the npm settings, I am now u ...

Utilizing AngularJS, implement ng-form and ng-repeat to seamlessly handle input validation and submission actions

Angular 1.6.2 I am experimenting with iterating over elements of a collection inputted by the user, checking their validity, and enabling the submit action if validation passes. I have tried using ng-form for this purpose and have come up with two differ ...

Is it possible for Angular2 to map a lone JSON object?

Dealing with a JSON response that is a single object, rather than an array, can be tricky. Recently in my project, I encountered a situation where I needed to map and use such a response from an API to fill out a template. It seemed like a simple task at f ...

Error message: Unable to locate the 'npm' task in Visual Studio Code

When attempting to execute a JavaScript or Python file in VS Code, an error message consistently pops up: Even after reinstalling node, the issue persists. Clicking on configure reveals various options, each leading me to a json file. New to coding, I ma ...

moodle - eliminate the need for grading at the same time

I'm currently setting up a Moodle installation and I'm looking for suggestions on how to prevent simultaneous grading. My goal is to have several evaluators grading students across various courses without any conflicts. If you have any recommend ...

The Chrome debugger will pause execution at a function without needing a DOM break point

Greetings! I am currently working on an angular js application. One issue that I have encountered is when I run the application and open the debugger by hitting F12, I notice that for every page it continuously calls a certain function and seems to stop th ...

The Ajax.ActionLink feature is causing the entire view to be duplicated and inserted into a <div> within the same view

Recently, I started learning MVC and taking on the task of developing an e-commerce application for my aunt's business. The challenge arises with a Product List page that includes a menu to search by category as a partial view. Initially, everything s ...

At what point does a selenium browser automatically shut down?

We've developed various test suites using selenium which all ran successfully when executed individually. However, when attempting to run the entire suite, the browser crashes unexpectedly and displays the error message below. org.openqa.selenium.Web ...

Anticipated input should be in the format of '_item_ in _collection_[ track by _id_]' but instead received

Having trouble with ng-repeat in AngularJS, only showing first element and getting a console error: Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '”pm'. angular.module('DataCabinet') .c ...

What is the best way to calculate the total of a field with matching Project and Employee names?

My task involves grouping data from an Array of objects by Project Name and Employee Name, whereby existing projects and employees have their hours added together. projects = [ { "project": { "id": 1, "name": "M ...

Finding the Attachment ID on a JIRA Issue Page with JavaScript

Currently, I am using an ajax call that requires the attachment id in its URL. The URL is hardcoded as follows: url: AJS.contextPath()+"/rest/api/latest/attachment/10415" jQuery.ajax({ url: AJS.contextPath()+"/rest/api/latest/attachment/10415", TYPE: "GET ...

retrieve object from s3 using angular and open it as a pdf

I'm attempting to access a file from an s3 bucket using Angular and display it as a PDF. I have a node service set up to retrieve the object, which I then call from Angular. However, when I try to open the PDF in Angular, it appears as a blank (white) ...

What is the best way to utilize the `Headers` iterator within a web browser?

Currently, I am attempting to utilize the Headers iterator as per the guidelines outlined in the Iterator documentation. let done = false while ( ! done ) { let result = headers.entries() if ( result.value ) { console.log(`yaay`) } ...

Duplicate the image from a specific div to another div, ensuring that only one clone is created

I'm trying to replicate an image in multiple spots within a frame, but I can only manage to get one instead of many. Can someone please tell me what I'm doing wrong? I am creating a map of terrain where I need to clone images from one div to anot ...

Utilize a single rails form to handle both AJAX and non-AJAX requests efficiently

In my Model, I have a simple_form that is used for the new action. The form is quite basic, as shown below: <%= simple_form_for @patient do |f| %> .... fields <% end %> Now, I want to be able to use this form in two different ways - withi ...

Constructing Browserify with dependencies containing require statements within a try-catch block

When attempting to integrate timbre.js (npm version) with Browserify, I encountered an issue where require statements for optional dependencies were enclosed in a try statement (check the source here). This resulted in a browserify build error displaying: ...

Scaling Images using HTML and CSS

Hey there, I'm currently learning web development and running into a bit of trouble with creating responsive images. Can anyone give me some guidance on what changes I should make in the code below? Here's the HTML code: <div class="caro ...