I have requirement where I want to select multiple categories and subcategories and send there ids as a query string using axios lets suppose if user has selected 2 categories having ids 1 and 2 and from these two categories he has selected subcategories having ids 31 and 65 so i want request url to be like this :
https://example.com/api/data?categories=1,2&subCategories=31,65
How can I achieve this desired format of url any help would be appreciated.
CodePudding user response:
Here you try this logic : (steps) :
- npm i axios
const axios = require("axios");
async function Api() {
const response = await axios.get("https://example.com/api/data",
{ params: { categories: '1,2' , subCategories : '31,65'} })
//receive data from request
console.log(response.data);
return response.data;
}
Api()
CodePudding user response:
To send multiple values for the same key in a query string using axios, you can specify an array of values for that key in the params object you pass to the axios.get() method. For example, you could use the following code to generate the URL you specified:
const axios = require('axios');
const categories = [1, 2];
const subCategories = [31, 65];
const params = {
categories: categories.join(','),
subCategories: subCategories.join(','),
};
const url = 'https://example.com/api/data';
axios.get(url, { params });
This would generate a URL that looks like this:
https://example.com/api/data?categories=1,2&subCategories=31,65
Alternatively, you could use the URLSearchParams API to generate the query string and append it to the URL manually. This would allow you to specify multiple values for the same key more directly, without having to use the join() method:
const axios = require('axios');
const categories = [1, 2];
const subCategories = [31, 65];
const searchParams = new URLSearchParams();
searchParams.append('categories', categories);
searchParams.append('subCategories', subCategories);
const url = 'https://example.com/api/data?' searchParams.toString();
axios.get(url);
This would also generate the same URL as before:
https://example.com/api/data?categories=1,2&subCategories=31,65