Guide on transferring JavaScript Objects from the Front End to Spring Boot Back-end and effectively processing and parsing them

After struggling with this issue repeatedly while developing my web apps, I've reached a breaking point and need some help. My frustration might come across as venting, but I'm genuinely stuck.

The challenge I'm facing is sending key-value pairs from my client (vanilla JS) to my backend (Spring Boot Java). Despite trying various approaches, I can't seem to find the right method or combination to achieve my goal. Below is the snippet of my current code that's not working:

Client-Side JS

var object = {
        'id' : 1,
        'username' : 'jumpthruhoops',
        'password' : 'melodysteez'
    };

    Axios
        .post('http://localhost:8080/gameSchedule', JSON.stringify(object))
        .then((response) => {
            console.log(response.data);
        });

Back-End Spring Boot/Java

@CrossOrigin
@RequestMapping(value = "/gameSchedule", headers = "Accept=application/json", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public String getSchedule(@RequestBody String user) {
    System.out.println(user);
    return "test";
}

The output I'm getting is somewhat close to what I expect. It shows a line like...

%7B%22id%22%3A1%2C%22username%22%3A%22tdellard1%22%2C%22password%22%3A%22sisters3%22%7D=

...which seems to be a hex code for the string object I passed in. I'm not sure if this is an issue with Spring Boot or caused by using JSON.stringify. Since the actual objects I plan on passing are more complex, I'd prefer not to deal with decoding the hex code unless there's no other solution.

Given the complexity, I don't want to use @RequestParams("name") String VariableName numerous times in the method parameter. Another method I tried involves @ModelAttribute and (@RequestBody User user), both resulting in errors. The most common error I encounter is:

018-10-30 23:38:29.346 WARN 12688 --- [io-8080-exec-10] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported]

With all these challenges, I need guidance on the best way to send data from Axios (form.serialize, JSON.stringify, JavaScript Object, etc.) and the corresponding method to process this data effectively on my Spring Boot Back-End, so I can work with it as a POJO.

Answer №1

When sending an object, it is important to use the object when receiving on the back-end side. Ensure that the name of the field in the request object matches the field name in the class on the back-end side, like so:

To access the fields and make changes in your code:

var data = {  
        'id' : 1,
        'username' : 'jumpthruhoops',
        'password' : 'melodysteez'
    };
// Variable name (data variable) can be anything but treat everything inside as the body

axios.post('http://localhost:8080/gameSchedule', JSON.stringify(object), {
        headers: {
            'Content-Type': 'application/json',
        }
    }
    );

Retrieve fields on the back-end side:

// Create a Student class to map fields with the body 

@CrossOrigin
@RequestMapping(value = "/gameSchedule", headers = "Accept=application/json", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public String getSchedule(@RequestBody Student student) {
    System.out.println(student.id);
    System.out.println(student.username);
    System.out.println(student.password);
    return "test"
}

Answer №2

To switch from using JSON.stringify(object) to simply passing the object, you can modify your Axios post request like this:

Axios
    .post('http://localhost:8080/gameSchedule', object)
    .then((response) => {
        console.log(response.data);
    });

For a detailed example of a POST request, check out the axios documentation here

In Spring Boot, you'll need to create an entity similar to the one below:

@Entity
public class UserAccount implements Serializable {

@Id
private Long id;

@Column(unique = true, nullable = false)
@Size(max = 255)
private String userName;

@Column(nullable = false)
@NotNull
private String password;

public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

public String getUserName() {
    return userName;
}

public void setUserName(String userName) {
    this.userName = userName;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

}

Then update your code with this snippet:

@CrossOrigin
@RequestMapping(value = "/gameSchedule", headers = "Accept=application/json", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public UserAccount getSchedule(@RequestBody UserAccount user) {
    System.out.println(user.getUserName());
    return user;
}

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

Error message in React JSX file: "Encountered an issue with 'createElement' property being undefined"

In the file test_stuff.js, I am executing it by using the command npm test The contents of the file are as follows: import { assert } from 'assert'; import { MyProvider } from '../src/index'; import { React } from 'react'; ...

Restrict the duration of time a user can spend in the v-calendar

I'm currently developing a project where users can request appointments. I'm utilizing the v-calendar library, which incorporates a datepicker. The challenge I'm facing is that users are able to request appointments at any time of day, 24/7 ...

What is the best way to retrieve the "data" from an Instagram API response?

I am encountering a similar response from the Instagram server. { "meta": { "code": 200 }, "data": { ... }, "pagination": { "next_url": "...", "next_max_id": "13872296" } } Is there a way to access ...

Guide for creating a function that accepts an array containing multiple arrays as input

I am working with a function called drawSnake and it is being invoked in the following manner: drawSnake( [ [0, 0], [0, 1], [0, 2], [0, 3], [0, 4], ] ); How should I format the input for this function? I have attempted using Array<Array<[numb ...

Utilizing Squelize's junction table for forming new connections: a comprehensive guide

I am currently working with three basic tables: A, B, and C. The relationship between A and B is many-to-many, so I am using a junction table called A_B. Table C has a one-to-many relationship with the junction table A_B. In sequelize, this is how they are ...

Update Material-ui to include an inclusive Datepicker widget

I have integrated the Material-ui Datepicker into my website to allow users to download timed event information from a database. The issue I am facing is that when users select two bracketing dates, events for the end date are not showing up correctly. F ...

I'm struggling to update a value in my view with Angularjs and Socket.io. It seems impossible to

In order to master AngularJS and NodeJS, I am embarking on creating a chatroom project. Everything seems to be functioning smoothly with Angular controllers and sending data to my NodeJS server using socket.io. However, I have encountered a problem: When m ...

Unable to convert JSON data for integration with rxjs

I am currently using a webSocket to receive data from my server. I have created an rx Subject called MessageEvent that allows me to retrieve the data. However, although I can successfully log the JSON data in my observable, I am unable to access any prope ...

Pick and modify a particular component in ReactJS

Currently, I am working on a project in ReactJS where I am attempting to toggle the colors of two buttons. While I have successfully set the active state property of the selected button, I am facing challenges with changing the style of another button (cal ...

The data shown in the C3.js tooltips

I have successfully created a chart like this on jsfiddle: http://jsfiddle.net/q8h39/111/ The chart includes customized tooltip contents for each plot. I attempted to add extra data to the tooltip using the "indexOf()" method, but unfortunately, it did no ...

Implement the use of NextAuth to save the session during registration by utilizing the email and password

When registering a user using email, password and username and storing in mongodb, I am looking to incorporate Next Auth to store sessions at the time of registration. My goal is to redirect the user in the same way during registration as they would experi ...

Angular JS is up and running

My journey into the world of Angular JS has just begun. While I can put together an Angular module, I find myself with a myriad of questions regarding the inner workings of Angular. How exactly does $scope function? I know that a root scope is created ...

The issue arises when the logout component fails to render even after the user has been authenticated. This problem resembles the one discussed in the React Router

While attempting to run the react-router docs example on the browser, I encountered an issue with the AuthButton component. The problem arises when the isAuthenticated value changes to true but the signOut button fails to display. import React from ' ...

Issue: Unable to access 'filter' property of null object

I've been working on a small react dropdown task and it's running smoothly in Google Chrome. However, I encountered an error when testing it on MS Explorer. Even after deploying it on a live server, the issue persisted. The specific error message ...

Error in JavaFX: CSS Parser anticipating COLON

Encountered an error and struggling to find the issue as everything seems right from my perspective: CSS Code: @font-face { font-family: 'Titillium'; font-style: normal; font-weight: normal; src: url('Titillium.ttf'); ...

My stored variable in the php session is not being recalled properly

Currently, my PHP script is generating new files based on user input. I want all documents to be created using the initial input to ensure consistency. In the first PHP script, I set the variable as follows: session_start(); $_SESSION["FirstName"] = $_POS ...

Experiencing issues with creating HTML using JavaScript?

I'm a JavaScript novice and struggling to figure out what's wrong with my code. Here is the snippet: var postCount = 0; function generatePost(title, time, text) { var div = document.createElement("div"); div.className = "content"; d ...

Tips for storing Appium capabilities in a JSON file and accessing them in your code

Below is the set of Appium capabilities used to execute a test: cap = new DesiredCapabilities(); cap.setCapability(CapabilityType.PLATFORM, "Android"); cap.setCapability(CapabilityType.VERSION, "5.1.0"); cap.setCapabil ...

What are the steps to ensure my MERN application refreshes properly when deployed on Heroku?

After successfully deploying my MERN app to Heroku, I encountered an issue where pages would come up blank when refreshed. Despite being able to navigate between pages using the nav bar without any errors, a page refresh renders them empty. This troublin ...

Converting the jQuery $.xajax loadmore feature into a custom XMLHttpRequest JavaScript function

I'm facing challenges while trying to create a XMLHttpRequest loadmore function as compared to using $.ajax. I am uncertain about what I might be missing in my code. Below is the function that is based on a previously working $.ajax version that I ha ...