如何用JavaScript向Spring Web API提交单值及多值JSON数据
用JavaScript提交嵌套JSON数据到Spring Web API
下面提供两种常用的实现方式,均可完成类似Postman的POST请求功能,提交包含普通字段和嵌套数组的JSON数据:
方法一:使用原生Fetch API
原生Fetch无需额外依赖,可直接在浏览器或Node.js环境使用:
// 构造要提交的JSON数据,结构与示例一致 const stockinData = { "id": 178, "stockin_date": "2022-11-15T08:18:54.252+00:00", "effective_date": null, "expired_date": null, "create_date": null, "update_date": null, "createby_emId": null, "updateby_emId": null, "deleteby_name": null, "delete_date": null, "invoice": "P_008", "po": "YSYDV", "remark": "Buy from PIC", "supply_id": 2, "stockinDetail": [ { "id": 272, "quantity": 10, "unit": "kg", "unit_price": 9, "stockin_id": 178, "pro_id": 74 }, { "id": 273, "quantity": 14, "unit": "kg", "unit_price": 2, "stockin_id": 178, "pro_id": 75 } ] }; // 发送POST请求到Spring API端点 fetch('http://your-spring-api-url/stockin', { method: 'POST', headers: { 'Content-Type': 'application/json', // 若API需要认证,添加对应头信息,例如:'Authorization': 'Bearer your-token' }, body: JSON.stringify(stockinData) // 将JS对象转为JSON字符串 }) .then(response => { if (!response.ok) { throw new Error(`HTTP错误!状态码:${response.status}`); } return response.json(); // 解析后端返回的JSON响应 }) .then(data => { console.log('提交成功,响应数据:', data); }) .catch(error => { console.error('提交失败:', error); });
关键说明
- 替换
http://your-spring-api-url/stockin为你的Spring Web API实际端点(对应后端@PostMapping注解的路径) Content-Type: application/json用于告知后端请求体为JSON格式,Spring会自动解析到对应实体类- 若API需要身份验证,在headers中添加对应的认证头即可
方法二:使用Axios库
Axios是更易用的HTTP客户端,简化了请求与错误处理,适合项目中频繁发起请求的场景:
第一步:引入Axios
- 浏览器环境:通过CDN引入
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
- Node.js环境:先安装再引入
npm install axios
const axios = require('axios');
第二步:编写请求代码
// 构造提交数据 const stockinData = { "id": 178, "stockin_date": "2022-11-15T08:18:54.252+00:00", "effective_date": null, "expired_date": null, "create_date": null, "update_date": null, "createby_emId": null, "updateby_emId": null, "deleteby_name": null, "delete_date": null, "invoice": "P_008", "po": "YSYDV", "remark": "Buy from PIC", "supply_id": 2, "stockinDetail": [ { "id": 272, "quantity": 10, "unit": "kg", "unit_price": 9, "stockin_id": 178, "pro_id": 74 }, { "id": 273, "quantity": 14, "unit": "kg", "unit_price": 2, "stockin_id": 178, "pro_id": 75 } ] }; // 发送POST请求 axios.post('http://your-spring-api-url/stockin', stockinData, { headers: { // 如需认证,添加头信息:'Authorization': 'Bearer your-token' } }) .then(response => { console.log('提交成功,响应数据:', response.data); }) .catch(error => { console.error('提交失败:', error.response?.data || error.message); });
关键说明
- Axios会自动将JS对象转为JSON字符串,并设置
Content-Type: application/json请求头 - 错误处理更便捷,可直接获取后端返回的错误详情(
error.response.data)
后端适配提示
确保你的Spring Web API实体类结构与提交的JSON匹配,示例如下:
// Stockin.java public class Stockin { private Integer id; private LocalDateTime stockin_date; private String invoice; private String po; // 其他字段省略... private List<StockinDetail> stockinDetail; // 对应嵌套数组的集合字段 // Getter、Setter、构造方法省略... } // StockinDetail.java public class StockinDetail { private Integer id; private Integer quantity; private String unit; private Double unit_price; private Integer stockin_id; private Integer pro_id; // Getter、Setter、构造方法省略... }
后端接口示例:
@RestController @RequestMapping("/stockin") public class StockinController { @PostMapping public ResponseEntity<Stockin> createStockin(@RequestBody Stockin stockin) { // 执行数据保存逻辑... return ResponseEntity.ok(stockin); } }
内容的提问来源于stack exchange,提问作者SopheaPhort
相关产品推荐
相关产品推荐

