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

Selenium Java code running into issues; The password field is not being populated

Trying to run a Java WebDriver code and Selenium test for a login page. Imported input from an Excel sheet that correctly assigns values to the username and password fields. However, upon clicking the login button: The submission of the login button work ...

chart.js version 3 does not display the correct date data on the time axis

Struggling to make chart.js work with a time axis is proving to be quite challenging for me. The code I have is as follows: <html> <head> <script src="https://cdn.jsdelivr.net/npm/moment"></script> <script src="https://cdnjs.clo ...

Tips for utilizing [(ngModel)] with an object that is empty, null, or undefined in Angular 4

When trying to assign [(ngModel)] inside my .html code to an empty (null or undefined) object, I encountered the error message _co.object is null. There are two scenarios: one where the object has a value and one where it does not. The ngModel works fine i ...

WordPress CSS & JS files failing to enqueue properly

My attempt to integrate my CSS and JS files with WordPress has not been successful. Although my CSS works through the Custom CSS tab, this is not an ideal solution. Below is the code from my functions.php file for your reference. Can you help me troublesho ...

Tips for incorporating a Survey Monkey website embed into an Angular application

I have a Survey Monkey account with multiple surveys. I am trying to embed a survey from this website into my Angular website, which already has Bootstrap and jQuery added. I attempted to directly add the script in an HTML component, but it did not work. ...

Surprising use of template string value

After following a tutorial, I decided to create ProductScreen.js and Product.js. However, when implementing my code, I encountered some warnings. Can anyone help me identify the issue? product.js import React from 'react' import Rating from &apo ...

The modal is not displayed when the on click listener is triggered

I'm a beginner in the world of programming and I'm currently working on creating modals that pop up when clicked. However, I'm facing an issue where the pop-up message doesn't appear when I click the button. Oddly enough, only the overl ...

Looking for the optimal method to display numerous lines of text in HTML, one by one, at intervals of 60 seconds?

I'm working on a display page for my website. The main text in the center needs to change every 60 seconds. I have over 150 individual lines of text that I want to cycle through on the page. What would be the most efficient way to load all these te ...

Significant issue identified with ajax functionality, requiring immediate attention

After executing the code in the console, I expected to see the ajax object with a readyState of 0 (as I aborted the ajax call). However, Chrome is displaying the number 4 in the console instead of 0. This discrepancy is surprising. http://jsfiddle.net/8yC ...

Is there a way to display the overall count of items in ReCharts?

I'm curious about how to access the additional data items within the 'payload' field of recharts when using material-ui. Despite my efforts to find relevant sources, I have not come across any references pertaining to accessing other group n ...

What is the best way to retrieve the information stored in an object?

let items = { 1001: {item: 'Chocolates', price: 10, quantity: 10}, 1002: {item: 'Biscuits', price: 10, quantity: 10}, 1003: {item: 'Bread', price: 20, quantity: 5}, 1004: {item: 'Milk', price: 25, quantity: 5}, 1005: ...

What is the best way to update information in a mongoose document using the _id field?

Although it may sound like a typical question, I've already conducted research and couldn't find a solution. I'm currently working on developing a discord bot and I don't have much experience in this area. The issue I keep encountering ...

Having trouble with a Vue3 project after running a Vite build in production mode?

When I run my project in development mode, everything works perfectly fine. However, when I build the project using `vite build´, some components stop functioning. Oddly enough, there are no errors displayed in the console or in the build logs. If I use ...

Browserify - combine external modules into a single bundle

I am a complete beginner in the world of browserify. I recently discovered this interesting module called peer-file, which allows for file transfer between two browsers. After reading the Usage section in its readme, I realized I needed to include the scri ...

Error handling middleware delivering a response promptly

Issue with my express application: Even after reaching the error middleware, the second middleware function is still being executed after res.json. As per the documentation: The response object (res) methods mentioned below can send a response to the cl ...

Leaving the "OK" button untouched in the sweet alert dialog

While implementing sweet alert in my project, I encountered an issue where the button text was not changing and the cancel button was missing on some pages. On certain pages, it only displayed OK. You can see a screenshot below for reference. https://i.s ...

Identifying the modifications made to a Firestore list, including additions, deletions, and changes

Utilizing Firestore as the backend has allowed me to navigate basic crud methods effectively. However, I am curious about how to identify changes within a list of returned items after the initial subscription. My goal is twofold: - Minimize the number of ...

Error: Kinetic.js cannot upload image to canvas

There must be something simple that I'm missing here. I've checked my code line by line, but for some reason, the image just won't load. var displayImage = function(){ var stage = new Kinetic.Stage("imgarea", 250, 256); var layer = new ...

Tips for creating a dynamic system to continuously add more HTML tables in PHP

I am working with an HTML table where the data is retrieved from a database. I need to add new rows to enter additional data, but the numbering does not continue from the last number. My question is how can I increase the numbering in the table. Please ref ...

What is the reason behind installing both Typescript and Javascript in Next.js?

After executing the command npx create-next-app --typescript --example with-tailwindcss my_project, my project ends up having this appearance: https://i.stack.imgur.com/yXEFK.png Is there a way to set up Next.js with Typescript and Tailwind CSS without i ...