Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default query params not getting passed in axios request

I'm using axios.create() to pass in a baseURL and some default query params like this

axios.create({
    baseURL: 'http://somebigurlhere',
    params: {
        part: 'part',
        maxResults: 5,
        key: 'key'
   }
});

When I use

axios.get('/search', {
    params: {
        q: 'word'
    }
});

the default params do not get merged in the GET call.

What I get is http://somebigurlhere/search?q=word

instead of http://somebigurlhere/search?part=part&maxResults=5&key=key&q=asd

I tried putting the configuration in many other ways but it still doesn't work. Am i doing something wrong here ?

I tried the same in other projects and it is working there. Just created a new react app with create-react-app and this doesn't seem to work anymore.

like image 501
pdjinn Avatar asked May 31 '19 14:05

pdjinn


People also ask

Can Post have request params?

POST should not have query param. You can implement the service to honor the query param, but this is against REST spec.


1 Answers

I solved it using 2 ways:

  1. 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',
       }
    });
    
  2. 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.

like image 121
AliF50 Avatar answered Oct 19 '22 08:10

AliF50