Search code examples
axiosedamam-api

Correct array in url in Axios


so I have started using Axios recently to create my first project. When I am trying to fetch data from the API, as default (i think) axios give me an URL like:

 /search?health[]=alcohol-free&health[]=celery-free&nutrient[]=calcium&nutrient[]=carbs

But the API (Edamam API) require:

/search?health=alcohol-free&health=celery-free&nutrients%5BCA%5D=100-&nutrients%5BFAT%5D=100

my parameters :

const params = {
    ...other,
    health:  ["alcohol-free", "celery-free"],
    nutrient: {
       CA: "100-200",
       FAT: "100" // under 100mg
    },
}

How can I correct my URL like that. I dont know where to fix the URL in axios. Thank you !


Solution

  • Use the qs package to stringify your request before you call axios

    const qs = require('qs')
    
    const params = {
        ...other,
        health:  ["alcohol-free", "celery-free"],
        nutrient: {
           CA: "100-200",
           FAT: "100" // under 100mg
        },
    }
    
    axios(qs.stringify(params))