vue.jsaxios

Axios config default GET param


I'm using Axios in my VueJS application and I want to add a default GET param in my request. I send my API-KEY through the URL ?api-key=secret and I don't want to specify this parameter each time.

I see in the documentation that we can set Global custom defaults. With that we don't have to specify the header each time. But can we do the same for get param ?


Solution

  • Here it is:

    axios.defaults.params = {}
    axios.defaults.params['api-key'] = secret
    

    axios.defaults.params = {}
    axios.defaults.params['api-key'] = 'secret'
    
    axios.get('https://echo.zuplo.io/')
      .then(({ data }) => console.log('No other query params:', data.query));
    axios.get('https://echo.zuplo.io/?query=inline')
      .then(({ data }) => console.log('Query params in URL:', data.query));
    axios.get('https://echo.zuplo.io/', {
      params: { query: 'params' },
    }).then(({ data }) => console.log('Query params via params option:', data.query));
    .as-console-wrapper { max-height: 100% !important; }
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>