java - POST 请求期间出现错误 400(错误请求)

标签 java reactjs rest post

我正在尝试从我的 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/

相关文章:

Java List<MyClass> 到 TreeMap<Long, MyClass>

java - 如何比较 java 中至少一个属性不同的相似对象的两个数组列表?

javascript - 从 URL 获取图像并在 React JS 中设置为背景

reactjs - 错误 : PostCSS plugin autoprefixer requires PostCSS 8. 更新 PostCSS 或降级此插件

java - Sonar 云插件因缺少类(class)而失败

C# Web API POST 时出现错误 404

api - Azure HBASE REST - colfam :col 的简单获取失败

rest - Magento REST API 签名无效

java - 发送 JSON 到 Endpoint 不起作用

java - 如何使用 Java ONVIF Web 服务从摄像头提取 ONVIF 事件