"Encountering a hiccup with AngularJS and Spring MVC: Error 400 - Bad

My attempt to post an object containing an ID (integer) and an array is resulting in a HTTP 400 Bad request response from the server side. Here's what I have so far...

Java Bean Object for Request:

public class GuardarVentaRequest {

private Integer idCliente;
private List<Venta> venta; ... (Getters and Setters code)

Java Object:

public class Venta {

private Integer id;
private String nombre;
private Integer precio;
private Integer cantidad;
private Integer total; ... (Getters and Setters code)

Java Controller:

@RequestMapping(value = "/guardarVenta", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody void venta(@RequestBody GuardarVentaRequest factura){
    System.out.println(factura);
}

AngularJS Service:

function guardarVenta(array){                                       
    let factura = {
        idCliente : parseInt($('#cliente').val()),
        venta : array,
    };
    console.log(factura);
    $http({
        method: 'POST',
        url: '/blue/guardarVenta',
        contentType: 'application/json',
        data: factura
    }).then(
    function successCallback(response){
        console.log(response.statusText);
    },
    function errorCallback(response){
        console.log(response.statusText);
    }
    );
}

Array:

$scope.products = new Array();
let productInfo = {
        id: $scope.product.id,
        name: $scope.product.name,
        price: $scope.product.price,
        quantity: $scope.quantityProduct,
        total: $scope.product.price * $scope.quantityProduct 
    }
    $scope.products.push(productInfo);

Output:

WARNING: Failed to read HTTP message: 
org.springframework.http.converter.HttpMessageNotReadableException: Could 
not read document: Can not construct instance of com.blue.beans.Venta: no 
suitable constructor found, can not deserialize from Object value (missing 
default constructor or creator, or perhaps need to add/enable type 
information?)
at [Source: java.io.PushbackInputStream@663359f3; line: 1, column: 28] 
(through reference chain: com.blue.beans.GuardarVentaRequest["venta"]-
>java.util.ArrayList[0]); nested exception is 
com.fasterxml.jackson.databind.JsonMappingException: Can not construct 
instance of com.blue.beans.Venta: no suitable constructor found, can not 
deserialize from Object value (missing default constructor or creator, or 
perhaps need to add/enable type information?)
at [Source: java.io.PushbackInputStream@663359f3; line: 1, column: 28] 
(through reference chain: com.blue.beans.GuardarVentaRequest["venta"]-
>java.util.ArrayList[0])

Chrome's Network Tab Output

Any suggestions?

Answer №1

Here are three suggestions to consider:

  1. Include a default constructor in GuardarVentaRequest and Venta classes.

    GuardarVentaRequest(){} & Venta(){}

  2. Verify if a HTTPMessageConverter has been configured in your Spring configuration. For example, you can use MappingJackson2MessageConverter (Make sure it is compatible with your Spring version).

  3. Attempt serializing the request payload using angular.toJson

I hope these recommendations prove beneficial!

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

`replaceWith function limited to single use`

I'm encountering an issue where the replaceWith function is only working on the first instance. Even though I am getting updated data, it's not being written to the div after the initial replacement. $( "#searchboxform" ).keyup(function() { ...

Manipulate JavaScript programmatically using Python and Selenium

Is it possible to programatically set up a Javascript override on a webpage using Selenium (either Geckodriver or Chromedriver) and Python? I have the modified JavaScript saved on my local computer. The procedure outlined in this Stack Overflow article w ...

Create a function in JavaScript that generates all possible unique permutations of a given string, with a special consideration

When given a string such as "this is a search with spaces", the goal is to generate all permutations of that string where the spaces are substituted with dashes. The desired output would look like: ["this-is-a-search-with-spaces"] ["this ...

ng-class: Issue detected - The symbol '-' is positioned at column {2}

I'm having an issue with ng-class. I need to add a disabled state class if the role has admin privileges, but I keep getting an error. Here is the HTML: <label class="toggle modal-label-box" ng-class="{state-disabled: checkCanModify()}"> &l ...

Combining AngularJS with Jquery Masonry to create dynamic layouts

Struggling to implement jQuery Masonry in my project. I have tried googling for solutions, but nothing seems to be working. This is my directive code: shout.directive("shoutList", function($timeout) { return { restrict : 'E', ...

The header of the bootstrap table will now feature a new button for toggling the visibility of the filter control

I'm currently utilizing a bootstrap table with filter control, and I am looking to incorporate a button (icon) on each of the table headers in order to toggle the visibility of the filter control. Is there a method to achieve this? An example of a b ...

encountering issues while Deserializing a collection containing children objects of various types

I am facing an issue with deserializing a JSON packet that consists of a header (under PACKET_HEADER) and several different types of messages (under DATA). These messages have a parent class in common: //parent message class public class Message { pu ...

What is the process for integrating the node-menu package into my project without utilizing the require statement?

Is there a way to incorporate node-menu into my TypeScript project without using require, like this: const menu = require('node-menu'); Whenever I attempt to import node-menu into my project, I encounter the following errors: https://i.sstatic. ...

Having trouble with sslforfree on Node.js Express.js platform

When attempting to set up an HTTPS server using Node.js and Express.js with sslforfree, I encounter an error 403: access denied when trying to access https://localhost. My folder structure looks like this: https://i.sstatic.net/NZqZT.png Below is my serve ...

Tips for utilizing a ForEach loop in JavaScript to create an object with dynamically provided keys and values

Looking to create a JavaScript object with the following structure, where the Car Make and Model Names are provided from other variables. { "Sedan":{ "Jaguar":[ "XF", "XJ" ], "AUDI":[ "A6", ...

"Ionic - The $state.go function functions properly during livereload but fails to work on the actual

I've encountered a strange issue with my code. When I use livereload or view the app in a browser, the state.go function functions correctly as expected. However, when I run the app on a device without livereload, the transition to the new state does ...

Jackson in Spring-MVC fails to interpret the JSON Object sent from JQuery

Utilizing Jackson, I am able to convert the object into JSON. @RequestMapping(value="getMessage.test", headers = "Accept=application/json" ,method = RequestMethod.POST) public @ResponseBody TestObject getMessage(){ TestObject object=new TestOb ...

Error encountered while updating in the midst of an ongoing state transition, e.g. within the `render` method

class MyComponent extends React.PureComponent { constructor(props) { super(props); this.state = { obj: [], externalObj: [], }; } fetchData = (external) => { ... arr = arr.filter(a => a.toLowerCase().includes(&ap ...

Issue with ngRepeat when deleting a child directive from a parent directive

I am encountering issues with a gallery manager component that allows the addition and removal of pictures. Here is the HTML code for the gallery handler: <img src = '{{snapshot}}' > <div class = 'md-button l3' is-file ng-mod ...

The Axios GET Request does not work when inside a while loop

Executing node index.js with this particular code snippet functions correctly. The process entails retrieving a random coordinate using the randomGeo function and then converting it to an address through an Axios call. Subsequently, the transPredtoJSON fun ...

The Jquery click event is not triggering when clicked from a hyperlink reference

I have a specific HTML href in my code snippet: <a id="m_MC_hl6_8" class="no_loaderbox button_link inline_block " href="somelink" target="_self">link</a> Upon clicking this link, a waiting box is displayed on the page. However, I don't ...

Setting a fixed data value within a div for subsequent retrieval through a function

I found a helpful example that demonstrates how to convert numbers into words. You can check it out here. The function for converting numbers into words is implemented in the following HTML code: <input type="text" name="number" placeholder="Number OR ...

Is it possible for the ServletContextListener to detect any changes that have occurred within the Web Application?

Is there a means to determine, within the ServletContextListener, the specific file within the web application that triggered the context to reload? Is it possible to identify if it was a JSP file or ascertain which .class file was modified? ...

It appears that the functionality of RegExp.prototype.exec() is not functioning as expected

const fs = require('fs') const jsdocFinder = /\/\*\*\n(.+?)\*\//gs /** * Implementing a function to convert JSDocs into JSON format. * @function * @param {String[] | String} dirs The directory or directories of ...

Tips for changing date format within Ajax javascript code

I am working with a JavaScript AJAX code: success:function(res){ var _html=''; var json_data=$.parseJSON(res.posts); $.each(json_data,function (index,data) { _html+='<span class=&apo ...