Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I override the set axios override defaults on specific requests?

when using axios promise library, it allows you to set query defaults to be used on all requests like this:

axios.defaults.baseURL = 'localhost:3000'
axios.defaults.headers.common['Token'] = window.localStorage.authtoken || null
axios.defaults.headers.post['Content-Type'] = 'application/json'

This has been fine while there was only one API to query, but now I have multiple API's my Client application needs to interract with, is there a way to set multiple baseURL's with their own configurations? Or is there a way to tell axios to ignore the defaults on a particular request?

// on specific urls I want to override the default base URL
axios.get('localhost:9000/whatever_resource')
.then(result => {
    // whatever
})
.catch(error => {
   // whatever
})
like image 253
alilland Avatar asked Nov 01 '17 19:11

alilland


1 Answers

You could set up an instance for each API, with their own base URLs: https://github.com/axios/axios#creating-an-instance

const firstAPI = axios.create({
    baseURL: 'http://first-api.com'
})
const secondAPI = axios.create({
    baseURL: 'http://second-api.com'
})

You can then use all the axios methods, like .get and .post on these instances:

firstAPI.get('hello')
  .then((response) => {
     console.log(response)
  })

secondAPI.post('world')
  .then((response) => {
     console.log(response)
  })
like image 140
Jamie McElwain Avatar answered Sep 28 '22 12:09

Jamie McElwain