Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Axios + query-string

I was wondering how I would be able to use query-string npm package to ease my axios calls. The package I use is: https://www.npmjs.com/package/query-string

An example:

import qs from 'query-string';
import axios from 'axios';

axios.get(`http://localhost:3000/api/products${qs.parse({ offset: 0, limit: 12 })}`);

Not sure why but this does not work as expected.

like image 709
kyapwc Avatar asked Jul 09 '26 04:07

kyapwc


2 Answers

You don't really need it. Axios has a standard way to put params into your request without any additional libraries or doing something manually.

axios
    .request({
      url: '/some/url',
      method: 'get',
      params: {
        offset: 0,
        limit: 12,
        unknown: '???'
      },
      ...
    })

Must be converted to /some/url?offset=0&limit=12&unknown=%3F%3F%3F.

like image 61
MartenCatcher Avatar answered Jul 11 '26 17:07

MartenCatcher


As there is no need to use query-string as axios does it automatically by putting the params into the request.

But still if you want to use the query-string package you can do it by this way.

Here is a short example which can give you somewhat idea of using query-string.

import qs from 'qs'; (https://www.npmjs.com/package/qs)
import axios from 'axios';

export default axios.create({
    baseURL: `http://localhost:3000/api/products`,
    params: (params) => {
        return qs.stringify(params, {offset: 0, limit: 12});
    },
});
like image 41
Ronak Khangaonkar Avatar answered Jul 11 '26 17:07

Ronak Khangaonkar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!