Reputation: 398
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.
Upvotes: 7
Views: 42212
Reputation: 326
this.$axios.get('/', {
params: {},
paramsSerializer: params => {
return qs.stringify(params);
}
})
Upvotes: 3
Reputation: 2887
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
.
Upvotes: 20
Reputation: 346
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});
},
});
Upvotes: 6
Reputation: 406
Axios
provides another handy yet powerful way to send your queryParams as object to http GET
method.
You may change your request this way:
axios.get('http://localhost:3000/api/products', {
params: {
offset: 0,
limit: 12
}
})
Upvotes: 5
Reputation: 86
In order to use template literals, you need to use the back-tick () not normal quotes.
CODE:
axios.get(`http://localhost:3000/api/products${qs.parse({ offset: 0, limit: 12 })}`);
If you dont want to use back-ticks, you cannot use ${}
syntax.
Just do it like normal string interpolation works.
axios.get(‘http://localhost:3000/api/products'+qs.parse({ offset: 0, limit: 12 })});
Upvotes: 0