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

Looking for a slideshow with interactive play buttons?

Looking for a slideshow similar to the one on the homepage of this site: Has anyone ever used a slideshow like that before? Any other references or help would be appreciated! ...

Ensuring consistency of Angular route data and maintaining data synchronization

In my Angular application, I have a table that displays a set of items and allows inline editing directly within the table. The data is fetched from an HTTP API through a service, which retrieves the data and injects it into the application. The issue ari ...

Tips on storing information within a Vue instance

Seeking a simple solution, all I need is to save data retrieved after an AJAX post in the Vue instance's data. See below for my code: const VMList = new Vue({ el: '#MODAL_USER_DATA', data: { user: []//, //userAcc: [] }, met ...

Leverage the power of ssh2-promise in NodeJS to run Linux commands on a remote server

When attempting to run the command yum install <package_name> on a remote Linux server using the ssh2-promise package, I encountered an issue where I couldn't retrieve the response from the command for further processing and validation. I' ...

The appearance of Bootstrap-Navbar is altered when viewed on a mobile device

After creating a website that was compatible with both web and mobile devices, I encountered an issue where the navbar would not collapse on my smartphone. However, when I resized the browser window to match the size of the smartphone screen, it worked per ...

How can I redirect to a different page with a keypress event in Next.js?

I am looking to implement a redirection function in nextjs when users press a key. There is a search input field where users can type and then hit the enter key to navigate to another page. Here's what I have attempted: const handleKeyPress = (e) = ...

What is the proper method to ensure that Unicode characters are escaped when converting a JSONObject to

Just like the query posted here, I am in search of a method to convert a net.sf.json.JSON object into a string representation using only ASCII characters. new JSONObject().put("JSON", "帮").toString(); should result in {"JSON":"\u5E2E"} instead o ...

Need to transfer a variable from the left side to the right side within Javascript. The instructor demonstrated using up and down as an

Recently started learning JavaScript as part of my college game programming course. I am only using Notepad for coding. Currently, I am trying to move an object (in this case, just the letter "o") from left to right on the screen. My professor has provided ...

What could be causing my HTML button to malfunction when attempting to navigate to a different section of the webpage?

Just starting out and developing my website. My hosting provider is IPage, but I'm running into an issue. When I click on a button to switch to another section of the site, it's not working as expected. Here's the code snippet: <button on ...

Steps to access the parent node key in Realtime Firebase Database

When data is pushed into the RealTime Firebase Database, it gets structured in JSON format. However, if there is a JSONObject within another JSONObject in the RealTime Database, how can we retrieve the "key" name of that inner JSONObject? The image below ...

Using ng-bind to Assign Default Value in HTML

Is there a way to set a default value for the scope that ng-bind can pick up without using ng-init? Currently, I am setting it like this: <button>Show <span data-ng-bind="data.text" data-ng-init="data.text = 'All';"></span> Nam ...

When hosted, OpenCart encounters a JavaScript error stating that the property "document" cannot be read because it is null

After successfully running opencart on my local machine, I encountered some errors upon uploading it to the hosting/server. The specific error message is as follows: Uncaught TypeError: Cannot read property 'document' of null f.each.contents @ j ...

What is the best way to implement a loading cursor when the Submit button is clicked?

Is there a way to incorporate a progress cursor into my code in order to notify the user to wait when they click the Submit button or the Upload Button while uploading multiple files? Below is an example of my form: <form action="" method="post" enct ...

Is there a way to enlarge images when hovered using canvas?

I came across a fascinating example at the following link: , where the images expand when hovered over. I am aware that this can be achieved using jquery, but I have concerns about its speed and reliability. I would like to experiment with d3.js, although ...

Console.log is not visible to jQuery's getJSON function

Currently, I am utilizing the getJSON method as shown below: $.getJSON("js/production-data.json").done(function(response) { console.log(response); console.log('hello'); }); While monitoring Firebug, the data retrieval process seems to ...

In ReactJS, when you encounter TextField values that are "undefined", it is important to handle them appropriately

I'm a beginner when it comes to ReactJs and Material-UI, so please bear with me if my question seems silly. Currently, I have a file named Main.js which includes the following code snippet: handleChange = (name, event) => { if(event==null) ...

Issue: AngularJS function parameters are undefinedWhen working with AngularJS

Why is the CarName function's parameter passing as undefined? Why is the actual value not being retrieved? var app = angular.module('myApp', []); app.controller('myCtrl', function ($scope) { $scope.carname = "Honda"; $sco ...

Tips for converting numbers in JavaScript and troubleshooting issues when trying to filter out non-numeric characters using Tel input commands

After finding this answer on how to convert digits in JavaScript, I attempted to apply the method to convert numbers in a phone number field with tel input type. function toEnglishDigits(str) { const persianNumbers = ["۱", "۲", &quo ...

I am interested in developing a streamlined method for locating a collection of elements on a webpage with an id attribute, regardless of their value, through the use of Selenium

Seeking a more efficient method to locate elements on a page with an id attribute using Selenium. Currently, I am using a for loop and checking getAttribute("id") != null on each element found by driver.findElements(By.xpath("//body//*" ...

Restrict the character count in Vue Material chips

Currently, I am utilizing the Vue Material Chips component to gather string arrays. My goal is to limit the character length of each string within the array to 30 characters. The component offers a md-limit prop which restricts the number of strings in th ...