我正在尝试从我的 react 应用程序向我的服务器发送 POST 请求,但我不断收到状态 400 错误请求错误。 异常(exception)是:
“org.springframework.http.converter.HttpMessageNotReadableException”。
错误消息是:
“JSON 解析错误:无法从 START_ARRAY token 中反序列化 java.util.LinkedHashMap 的实例;嵌套异常是 com.fasterxml.jackson.databind.JsonMappingException:无法从 START_ARRAY token 中反序列化 java.util.LinkedHashMap 的实例START_ARRAY token \n 位于 [来源:java.io.PushbackInputStream@6a188b06;行:1,列:1]"
我尝试使用POSTMAN测试API,但我仍然不断收到相同的错误。
@PostMapping("/cart")
public Cart create(@RequestBody CartRequest cartRequest){
return cartRepository.save(new Cart(0,cartRequest.getProductname()));
}
我的模型类是
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 + '\'' +
'}';
}
}
存储库类如下
public interface CartRespository extends JpaRepository<Cart, Integer> {
}
请求代码如下
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 });
}
发送请求的Button如下
{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>)}
我想要执行的是从产品接收信息并将其添加到购物车。
已使用 GET 请求接收产品信息。
最佳答案
使 Controller 的方法如下所示:
@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));
}
顺便说一句,您可以接收 json 作为模型,而不是 Map。您最好创建一个新的模型类 - CartRequest,现在只有一个字段 - productname
,并在 Controller 中接受该模型
@PostMapping("/cart")
public Cart create(@RequestBody CartRequest cartRequest){
return cartRepository.save(new Cart(0, cartRequest.getProductname()));
}
如您所见,我没有说在模型中包含 productid
字段。这是因为你的实体在被 ORM 保存时必须没有 id(例如 hibernate)
关于java - POST 请求期间出现错误 400(错误请求),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54849496/