javascript - Axios multiple values (comma separated) in a parameter - Stack Overflow

Expected query string:http:fqdnpage?categoryID=1&categoryID=2Axios get request:fetchNumbers () {

Expected query string:

http://fqdn/page?categoryID=1&categoryID=2

Axios get request:

fetchNumbers () {
  return axios.get(globalConfig.CATS_URL, {
    params: {
      ...(this.category ? { categoryId: this.category } : {})
    }
  })
    .then((resp) => {
      // console.log(resp)
    })
    .catch((err) => {
      console.log(err)
    })
}

As you can see, it works perfectly with just 1 value for 1 parameter, but if i wanted to make multiple values - it doesn't work, i've tried to use an array:

...(this.category ? { categoryId: [1, 2] } : {})

But it returns this way:

http://fqdn/page?categoryID[]=1&categoryID[]=2

So it just not working. Had a look at this issue: Passing an object with a parameter with multiple values as a query string in a GET using axios

But can't figure out, how he solved this problem.

Expected query string:

http://fqdn/page?categoryID=1&categoryID=2

Axios get request:

fetchNumbers () {
  return axios.get(globalConfig.CATS_URL, {
    params: {
      ...(this.category ? { categoryId: this.category } : {})
    }
  })
    .then((resp) => {
      // console.log(resp)
    })
    .catch((err) => {
      console.log(err)
    })
}

As you can see, it works perfectly with just 1 value for 1 parameter, but if i wanted to make multiple values - it doesn't work, i've tried to use an array:

...(this.category ? { categoryId: [1, 2] } : {})

But it returns this way:

http://fqdn/page?categoryID[]=1&categoryID[]=2

So it just not working. Had a look at this issue: Passing an object with a parameter with multiple values as a query string in a GET using axios

But can't figure out, how he solved this problem.

Share asked Sep 24, 2018 at 15:01 Alexander KimAlexander Kim 18.4k24 gold badges107 silver badges165 bronze badges 1
  • You should check this answer. – aaguilera Commented Apr 19, 2023 at 10:31
Add a ment  | 

3 Answers 3

Reset to default 6

You can use Axios's paramsSerializer to customize the serialization of parameters in the request.

Note that URLSearchParams serializes array data the way you're expecting:

const searchParams = new URLSearchParams();
searchParams.append('foo', 1);
searchParams.append('foo', 2);
console.log(searchParams.toString()); // foo=1&foo=2

So you could use that class in paramsSerializer as follows:

// my-axios.js
export default axios.create({
  paramsSerializer(params) {
    const searchParams = new URLSearchParams();
    for (const key of Object.keys(params)) {
      const param = params[key];
      if (Array.isArray(param)) {
        for (const p of param) {
          searchParams.append(key, p);
        }
      } else {
        searchParams.append(key, param);
      }
    }
    return searchParams.toString();
  }
});

// Foo.vue
import axios from './my-axios.js';

export default {
  methods: {
    async send() {
      const { data } = await axios({
        url: '//httpbin/get',
        params: {
          categoryId: [1, 2, 3]
        }
      });

      // ...
    }
  }
}

demo

This is not an axios related issue. It depends on whether your backend service is able to understand query params in this fashion(seems to be framework dependent). From your question, I think it is not working when queryParams like following are sent

?categoryID[]=1&categoryID[]=2

and it expects

?categoryID = 1,2

What you can do is transform array to such string before passing it to params in axios. Update the following piece in your code and it should solve your problem.

...(this.category ? { categoryId: this.category.join(',') } : {})

Take a look at following thread

How to pass an array within a query string?

If you are here looking for how to achieve ma separated values like this:

?size=4&sort=modifiedOn,name

Do this:

const http = axios.create({

  paramsSerializer: params => new URLSearchParams(params).toString()

})

http.get('/users', {
  params: {
    size: 4,
    sort: ['modifiedOn', 'name']
  }
})

Results in serialised query sting:

?size=4&sort=modifiedOn%2Cname

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1743679162a4489080.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信