乐闻世界logo
搜索文章和话题

How to correctly use axios params with arrays

1个答案

1

When using Axios for API calls, you may need to send array-type parameters to the server. Proper handling of array-type parameters depends on how the server parses the parameters. Generally, there are several ways to submit array-type parameters:

1. Passing Arrays via Query Strings

You can convert the array into a query string format, for example:

shell
GET /endpoint?param[]=value1&param[]=value2

In Axios, you can simply pass the array directly as a parameter, and Axios will automatically serialize it into a query string:

javascript
axios.get('/endpoint', { params: { param: ['value1', 'value2'] } });

Axios will serialize the request to /endpoint?param=value1&param=value2.

2. Customizing Serialization with paramsSerializer

If you need to customize how the array is serialized into a query string, you can use the paramsSerializer function. For example, if you want to use a comma-separated array:

javascript
import qs from 'qs'; // Using the qs library for query string serialization axios.get('/endpoint', { params: { param: ['value1', 'value2'] }, paramsSerializer: params => { return qs.stringify(params, { arrayFormat: 'comma' }) } });

This will serialize the request to /endpoint?param=value1,value2.

3. Sending Arrays as JSON in POST Requests

If you are sending a POST request and need to include the array in the request body, you can send the array as a JSON object:

javascript
axios.post('/endpoint', { arrayParam: ['value1', 'value2'] });

This way, the array is sent as part of the JSON payload to the server.

Example Suppose there is an API endpoint /search that receives an array-type parameter tags to filter search results. Using the query string approach, you can call the API as follows:

javascript
axios.get('/search', { params: { tags: ['frontend', 'javascript', 'react'] } });

If the server expects a comma-separated string instead of multiple identical keys, you can use the paramsSerializer to customize the serialization:

javascript
import qs from 'qs'; axios.get('/search', { params: { tags: ['frontend', 'javascript', 'react'] }, paramsSerializer: params => { return qs.stringify(params, { arrayFormat: 'comma' }); } });

The above methods are common approaches for handling array-type parameters. The specific method to use depends on the expected format of the backend API, so in practice, you should select the appropriate array serialization method based on the server's requirements.

2024年6月29日 12:07 回复

你的答案