Default query params not getting passed in axios request
I solved it using 2 ways:
Using default params and spreading them when using the request
export const API_DEFAULT_PARAMS = { part: 'part', maxResults: 5, key: 'key'}export default axios.create({ baseURL: 'http://somebigurlhere',});
Then to use it:
import api, { API_DEFAULT_PARAMS } from './place/where/previous/file/is'; ....api.get('/search', { params: { // spread the default params ...API_DEFAULT_PARAMS, // add your own parameters here q: 'word', }});
Using interceptors as a user suggested here
const instance = axios.create({ baseURL: 'http://somebigurlhere',}); instance.interceptors.request.use(config => { config.params = { // add your default ones part: 'part', maxResults: 5, key: 'key', // spread the request's params ...config.params, }; return config;});export default instance;
Then to use it
import api from './place/where/previous/file/is';...api.get('/search', { params: { q: 'word', }});
I like the interceptor approach more because it abstracts the default params to the instance file itself and you don't have to import and spread an object every time you use the instance.
Downgrade the Version of axios. it has some issues with latest version
npm install --save axios@0.18.1
Use should return a custom object like this
const custom = axios.create({ baseURL: 'http://somebigurlhere', params: { part: 'part', maxResults: 5, key: 'key' }});
Then use the custom object to make request
custom.get('/search', { params: { q: 'word' }});
Please try similar example in this codepen
Then you will see in the console, the query parameters are merged together in the request (blue line) as following image