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.
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
.
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}); }, });
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
}
})
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 })});
this.$axios.get('/', {
params: {},
paramsSerializer: params => {
return qs.stringify(params);
}
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.