Shenal Burkey
Shenal Burkey

Reputation: 37

Error 400 (Bad request) during POST request

I'm trying to send a POST request to my server from my react application but however i keep getting a status 400 Bad Request error. The exception is:

"org.springframework.http.converter.HttpMessageNotReadableException".

The error message is:

"JSON parse error: Can not deserialize instance of java.util.LinkedHashMap out of START_ARRAY token; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.LinkedHashMap out of START_ARRAY token\n at [Source: java.io.PushbackInputStream@6a188b06; line: 1, column: 1]"

I tried testing the API with POSTMAN but i still keep getting the same error.

@PostMapping("/cart")
public Cart create(@RequestBody CartRequest cartRequest){
  return cartRepository.save(new Cart(0,cartRequest.getProductname()));
}

My models class is

public class CartRequest {
String productname;

public CartRequest(int productid, String productname) {
    this.productname = productname;
}


public String getProductname() {
    return productname;
}

public void setProductname(String productname) {
    this.productname = productname;
}

@Override
public String toString() {
    return "CartRequest{" +
            ", productname='" + productname + '\'' +
            '}';
}
}

The repository class is follows

public interface CartRespository extends JpaRepository<Cart, Integer> {
    }

The request code is as follows

import React, { Component } from "react";
import axios from 'axios';
import NavBar from "./navbar";
export default class Products extends Component {
state = {
    isLoading: true,
    groups: [],
};

constructor(props){
    super(props);
    {
         this.add = this.add.bind(this);
    }
}
add(id, name) {
    axios({
    method: 'post',
    url: '/api/cart',
    body: {
      productid: id,
      productname: name
    }
  });
}

async componentDidMount() {
    const response = await fetch('api/product');
    const body = await response.json();
    this.setState({ groups: body, isLoading: false });
}

The Button that sends the requests is as follows

{this.state.groups.map(group => <button key={group.id} onClick={() => this.add(group.productid, group.name)} className="flex-c-m size1 bg4 bo-rad-23 hov1 s-text1 trans-0-4">Add to Cart</button>)}

What I'm tryinig to perform is to recieve the information from a product and add it to a shopping cart.

The information of the product has been received using a GET request.

Upvotes: 0

Views: 2711

Answers (1)

Andrey Antipov
Andrey Antipov

Reputation: 410

Make your controller's method looks like this:

@PostMapping("/cart")
public Cart create(@RequestBody Map<Integer, Integer> body){
    int productid = body.get("productid");
    String productname=body.get("productname");

    return cartRepository.save(new Cart(productid, productname));
}

By the way, you can receive your json as a model, not a Map. You'd better create a new model class - CartRequest with one field for now - productname, and accept taht model in the controller

@PostMapping("/cart")
public Cart create(@RequestBody CartRequest cartRequest){ 
  return cartRepository.save(new Cart(0, cartRequest.getProductname()));
}

As you can see, I didn't say to include productid field in the model. This is because your entity has to have no id when it gets saved by ORM (e.g. hibernate)

Upvotes: 1

Related Questions