Vue axios在Spring Boot 的 Controller中接收数组类型的参数
在 Spring Boot 的 Controller 中,你定义了一个 POST 请求的接口,该接口接收两个参数:一个 String 类型的 ip 参数和一个 String[] 类型的 domain 参数。现在我们来看看如何使用 Vue 的 axios 发送 POST 请求来调用这个接口。
Spring Boot Controller 示例
@PostMapping("/blockipdomainbytenantcdn")
public ResultMap blockIpDomainByTenantcdn(@RequestParam("ip") String ip, @RequestParam("domain") String[] domain) {// 处理逻辑return new ResultMap();
}
Vue 中使用 axios 调用接口
在 Vue 中,使用 axios 发送 POST 请求时,你可以通过 FormData 或 URLSearchParams 的形式来传递 @RequestParam 参数。
1. 使用 axios 发送 POST 请求
import axios from 'axios';const ip = '192.168.1.1';
const domain = ['example.com', 'test.com'];// 使用 URLSearchParams 来传递参数
const params = new URLSearchParams();
params.append('ip', ip);
domain.forEach(d => params.append('domain', d));axios.post('/blockipdomainbytenantcdn', params).then(response => {console.log(response.data);}).catch(error => {console.error(error);});
说明
-
URLSearchParams:我们使用URLSearchParams来构建表单参数。append方法用于向参数列表中添加一个键值对。对于数组domain,需要对每个元素调用append方法,确保参数以domain=example.com&domain=test.com的格式发送。 -
axios.post:axios.post方法发送POST请求,并将params作为请求体传递。
生成的请求体
通过这种方式,axios 会发送一个 application/x-www-form-urlencoded 类型的请求,生成的请求体会类似于:
ip=192.168.1.1&domain=example.com&domain=test.com
处理响应
在 then 方法中处理服务器返回的响应数据,并在 catch 方法中处理可能发生的错误。
a. 探索如何在 POST 请求中使用 JSON 格式发送数据。
b. 学习如何在 axios 请求中添加自定义头信息(如 Content-Type、Authorization 等)。
