Error: Unsupported Media Type when attempting to send JSON data from an AngularJS frontend to a Spring controller

Below is the controller function code snippet

@RequestMapping(value = "/logInChecker", method = RequestMethod.POST, consumes = {"application/json"})
    public @ResponseBody String logInCheckerFn(@RequestBody UserLogData userLogData){
        Integer userAuthFlag = goAnalyserModel.checkUserAuth(userLogData);
        return userAuthFlag.toString();
    }

This is my Bean class

public class UserLogData {

private String userName;
private String password;

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

}

Included here is the html file with angularjs functionality

<!DOCTYPE html>
<html lang="en" ng-app="nameAppIndexPage">
   <head>
      <meta charset="utf-8">
      <title>Go Analyser - Login</title>
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta name="description" content="">
      <meta name="author" content="">
      <!-- Le styles -->
      <link href="assets/css/bootstrap.css" rel="stylesheet">
      <style type="text/css">
         body {
         padding-top: 60px;
         padding-bottom: 40px;
         }
      </style>
      <link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
   </head>
   <body ng-controller="nameController">
      <div class="navbar navbar-inverse navbar-fixed-top">
         <div class="navbar-inner">
            <div class="container">
               <a class="brand" href="#">Go Analyser</a>
            </div>
         </div>
      </div>
      <div class="container">
         <div class="row">
           <div class=" margin_alignment"></div>
            <div class="span4"></div>
            <div class="span4">
               <form class="form-signin">
                  <label for="exampleInputEmail1">Email address</label>
                  <input type="text" class="input-block-level" placeholder="Email address" ng-model="userName">
                  <label for="exampleInputPassword1">Password</label>
                  <input type="password" class="input-block-level" placeholder="Password" ng-model="password">
                  
                  <button type="submit" ng-click='checkLogin()'>login</button>
               </form>

            </div>
            <div class="span4"></div>
         </div>
         <footer>
         </footer>
      </div>
      <script src="assets/js/jquery.js"></script>
      <script src="assets/js/angular.js"></script>


      <script>
                    var myApp = angular.module('nameAppIndexPage',[]);
                    myApp.controller('nameController',function($http,$scope){
                        $scope.checkLogin = function(){
                            alert("inside checklogin()");

                            var userName = $scope.userName;
                            var password = $scope.password;

                            var dataToSend = {
                                "userName" : userName,
                                "password" : password   
                            };
                            console.log(dataToSend);
                            alert("after data to send");  
                            $http.post('logInChecker',dataToSend).success(function(data){
                                if(data == 1){
                                    alert("inside loginSuccess");
                                }else{
                                    alert("username and password mismatch");
                                }
                            }).error(function(data){
                                alert("error in post" + JSON.stringify({data: data}));
                            });
                        }
                    });
               </script>
   </body>
</html>

I am experiencing an unsupported media error in the browser console while trying to communicate between the AngularJS function and Spring controller. Everything looks correct but I cannot figure out the issue.

Answer №1

When encountering this message, it could indicate that the request cannot be converted to a Java object or vice versa.

In your specific case, it seems to be the former scenario. Here are a few things you may want to verify:

  1. Check if you have included <mvc:annotation-driven /> in your servlet configuration

  2. Ensure that you have the necessary Jackson dependencies on your classpath. For Spring 4.x, use Jackson 2.x version; for Spring 3.x, opt for Jackson 1.9

To ensure proper conversion of your response, along with having the required dependencies, make sure that

  1. Either an Accept header is included in your request with the value application/json, or the RequestMapping annotation in your handler method specifies produces = {"application/json"}

Answer №2

Include the @JsonProperty annotation with the name of your property in the bean class. Monitor JSON POST requests using the browser's developer tools.

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

Sorting data in Angular using the orderBy filter and managing data

Is there a way to effectively sort table data when it is spread across multiple tables? I'm currently faced with the challenge of displaying app data in tables based on the country it belongs to, meaning that each country has its own table of app data ...

Angular: Observing changes in the store and sending a message from a Service component to another component once the Service has finished specific tasks

Within our codebase, we introduce two classes known as GetDataAsyncService. This service is designed to wait for a change in the store before executing the block of code contained within it. By utilizing observables and subscribing to data changes with t ...

Can you explain the concept of binding and unbinding in jQuery?

Can you explain the concepts of binding and unbinding in jQuery in simple terms for someone who learns slowly? ...

Stop Swiper Slide from moving when clicked on

I am currently utilizing Swiper JS and have encountered an issue. In my Swiper slider, each slide contains a button. Whenever I click on the slide or the button itself, the slide becomes the active one, causing the entire slider to move. Is there a way to ...

Incorporating CSS Styles in EJS

Struggling with connecting my CSS files while using EJS. I've checked out another solution but still can't seem to get it right. Here is the code I used as a reference for my CSS file. EJS <html> <head> <meta charset="utf-8 ...

Hide the content within a table row by setting the display to

I need to hide the div with the id "NoveMeses" if all h3 elements display "N.A." Is there a way to achieve this? If both h3 elements in row1 and row2 contain the text "N.A.", I want the div NoveMeses to be hidden. Below is the code snippet using AngularJ ...

Leveraging PHP to construct a TABLE based on JSON data

Recently, I delved into learning PHP and successfully retrieved the JSON data I needed. However, I hit a roadblock when attempting to construct a table using this data. Despite my trial-and-error approach, I find myself stuck at this point. The current st ...

Manipulate HTML content from JSON data in JavaScript without using jQuery

The information stored in the texts.json file: [{ "PageTextKeyId": 1, "PageTextKeyName": "page-first-text", "PageTextValueName": "Lorem ipsum dolor sit amet" }, { "PageTextKeyId": 2, "PageTextKeyName": "after-page-first-text", "PageTextValueNa ...

The jQuery function appears to be running multiple times in a loop

For some reason, every value in my JSON object is getting added to the "listOfCountries" array twice. It seems like there might be a loop going through the result object more than once. I could really use some assistance with this issue! var listOfCountri ...

Getting row data from ag-grid using the angular material menu is a straightforward process

I have a specific requirement in ag-grid where I need to implement a menu to add/edit/delete row data. Currently, I am using the angular material menu component as the cell template URL. However, I am facing an issue where when I click on the menu item, it ...

What limitations prevent me from using "await .getAttribute()" in Protractor, despite the fact that it does return a promise?

I have been working on transitioning my Protractor tests from using the selenium control flow to async/await. However, I am facing an issue where it is not allowing me to use await for the .getAttribute() function. Each time I try, I receive the error mess ...

NextJS - Error: Invalid JSON format, starting with a "<" symbol at position 0

After following a tutorial on NextJS, I attempted to make some modifications. My goal was to include the data.json file on the page. However, I kept encountering the error message "Unexpected token < in JSON at position 0." I understand that I need to ...

Encountering an issue while attempting to parse an XML file with AJAX

I am running into an issue in my .html file while using AJAX to display an xml file. My setup includes a button that should be able to read in both a json and an xml file. Strangely, the json button works perfectly fine, but when I try to use the xml butto ...

Experiencing an excessive number of re-renders can be a common issue in React as it has limitations set in place to prevent infinite loops. This

I have integrated React context to access the login function and error from the context provider file for logging into the firebase database. I am trying to display any thrown errors in the app during the login process. However, I encountered an issue whe ...

Retrieve data from a specific field in a JSON response

I am attempting to retrieve a specific field from an API request, which will be utilized for another task. My goal is to automate this request in order to keep track of the timestamp of the remote machine. Here is the script I have created to obtain the j ...

Is there a way to dynamically change the helperText of a Material UI TextField using its current value through code?

I'm currently attempting to dynamically change the helperText of a Material UI TextField based on the value entered into the field. Below is my current implementation: const defaultScores = { STR: 10, DEX: 10, CON: 10, INT: 10, WIS: 10, CH ...

Tally up the occurrences of each item in the array and provide the result in the form

Is there a built-in method in JavaScript to convert an array like: const colorArray = ['red', 'green', 'green', 'blue', 'purple', 'red', 'red', 'black']; into an object that c ...

Clicking on Rows in DataTables: Enhancing

I have been utilizing the jquery datatables plugin, and have encountered an issue with the row click functionality. Strangely, it only seems to work on the first page of the table. When I navigate to any subsequent pages, the row click fails to respond whe ...

Tips for retrieving the most recent UI updates after the container has been modified without the need to refresh the browser

Currently, I have developed a micro frontend application in Angular using module federation. This application is hosted in production with Docker containers. My main concern revolves around how to update the UI changes for the user without them needing to ...

Merging and collaborating on a variety of JSON documents

I have limited experience working with JSON files and I'm facing some challenges. The software I'm using generates a separate JSON file for each image it processes, resulting in hundreds of individual JSON files at any given time. My main struggl ...