通过 Reactjs 以 Json 格式发布请求
Posted
技术标签:
【中文标题】通过 Reactjs 以 Json 格式发布请求【英文标题】:Post Requrst in Json Format through Reactjs 【发布时间】: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
)
);
【问题讨论】:
【参考方案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
【讨论】:
以上是关于通过 Reactjs 以 Json 格式发布请求的主要内容,如果未能解决你的问题,请参考以下文章
通过在jquery中添加函数发送ajax请求来加载数据库数据,以json的格式发送到页面
在 Javascript/Reactjs 中使用 Fetch API 和 map() 显示 JSON 数据