【问题标题】:Post Requrst in Json Format through Reactjs通过 Reactjs 以 Json 格式发布请求
【发布时间】:2020-12-31 11:58:07
【问题描述】:

我必须从 reactjs(前端)调用一个发布请求到 spring boot(后端)。我需要知道如何通过 reactjs 调用以下 json 请求。

在 Spring Boot 中,我有以下课程

产品类别

@Entity
@Table(name = "PRODUCT",schema = Schema.ASSIGNDB,uniqueConstraints = {
        @UniqueConstraint(name = "productName",columnNames = "PRODUCT_NAME")
})
@Getter
@Setter
public class Product {

    @Id
    @SequenceGenerator(name = "PRODUCT_ID_GEN",sequenceName = Schema.ASSIGNDB+".PRODUCT_ID_SEQ",initialValue = 1003,allocationSize = 1)
    @GeneratedValue(generator = "PRODUCT_ID_GEN",strategy = GenerationType.SEQUENCE)
    @Column(name="PRODUCT_ID")
    private int productId;

    @Column(name = "PRODUCT_NAME",nullable = false)
    private String productName;

    @Column(name = "NUMBER_OF_UNIT",nullable = false)
    private int numberOfUnitInCartoon;

    @Column(name = "PRICE_OF_CARTOON",nullable = false)
    private double priceOfCartoon;



    @Column(name="URL_OF_IMAGE")
    private String urlOfImage;
}

ProductTotal 类

@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
public class ProductTotal {

    private Product product;
    private int quantity;
}

TotalPrice 类

@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
public class TotalPrice {

   private List<ProductTotal> productTotal;
   private double totalPrice;

}

PriceController 类

@CrossOrigin(origins = "*",maxAge = 3600)
@RestController
@RequestMapping("/price")
public class PriceController {

 @PostMapping(value = "/total",consumes = {MediaType.APPLICATION_JSON_VALUE},produces = {MediaType.APPLICATION_JSON_VALUE})
    private ResponseEntity<TotalPrice> getTotalPrice(@RequestBody TotalPrice totalPrice)
    {
        if(totalPrice.getProductTotal().size()!=0)
            return new ResponseEntity<>(priceService.getTotalPrice(totalPrice),HttpStatus.OK);
        else
            throw new NullPointerException();
    }

}

json格式应该是这样的

{
"productTotal": [
    {
     "product":{
        "productId": 1001
     },
     "quantity":25
    },
    {
     "product":{
         "productId": 1003
     },
     "quantity":15
    }

]

    }

我必须通过 reactjs 作为发布请求传递上述格式

fetch('http://localhost:9090/price/total2',{
            method:'POST',
            headers: {'Content-Type':'application/json'},
            body: JSON.stringify({
                productTotal:{
                   // i have no idea how to write this, can anyone help
                }
            })
        }).then(res=>res.json)
        .then(result=>{
            console.log(`your result ${result}`);
        },error=>{
            this.setState({
                isLoaded:true,
                error
            })
        });

【问题讨论】:

    标签: javascript java json reactjs spring-boot


    【解决方案1】:

    在我看来对象应该是这个,除非我遗漏了什么:

    productTotal: [
        {
          product: {
            productId: 1001
          },
          quantity: 25
        },
        {
          product: {
            productId: 1003
          },
          quantity: 15
        }
      ]
    

    【讨论】:

      【解决方案2】:

      你需要像这样发送对象

      { 
       "product_total": [{
           "quantity":10,
           "product": {
               "product_id": 1,
               "product_name": "name",
               "numberOfUnitInCartoon":"..."
               "price_of_cartoon": 1,
               "url_of_image": "..."
           }
       },
       ...
       ],
       "total_price":123
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-09-03
        • 2018-04-25
        • 2021-03-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多