在 Axios 中,当你需要传递数组参数时,可以使用以下几种方式进行格式化:
- 使用 paramsSerializer 将数组转换为逗号分隔的字符串: import axios from 'axios';import qs from 'qs';const arrayParams = ['param1', 'param2', 'param3'];axios.get('https://api.example.com/endpoint', {params: { array: arrayParams },paramsSerializer: (params) => qs.stringify(params, { arrayFormat: 'comma' }),}).then((response) => console.log(response)).catch((error) => console.error(error));这将发送一个类似于以下的请求: https://api.example.com/endpoint?array=param1,param2,param3
- 使用 indices格式(默认行为):axios.get('https://api.example.com/endpoint', {params: { array: arrayParams },}).then((response) => console.log(response)).catch((error) => console.error(error));这将发送一个类似于以下的请求: https://api.example.com/endpoint?array[0]=param1&array[1]=param2&array[2]=param3
- 使用 brackets格式:axios.get('https://api.example.com/endpoint', {params: { array: arrayParams },paramsSerializer: (params) => qs.stringify(params, { arrayFormat: 'brackets' }),}).then((response) => console.log(response)).catch((error) => console.error(error));这将发送一个类似于以下的请求: https://api.example.com/endpoint?array[]=param1&array[]=param2&array[]=param3
- 使用 repeat格式:axios.get('https://api.example.com/endpoint', {params: { array: arrayParams },paramsSerializer: (params) => qs.stringify(params, { arrayFormat: 'repeat' }),}).then((response) => console.log(response)).catch((error) => console.error(error));这将发送一个类似于以下的请求: https://api.example.com/endpoint?array=param1&array=param2&array=param3注意,使用 paramsSerializer需要安装并导入qs库。你可以使用以下命令安装它:npm install qs或 yarn add qs