Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the default base url for axios

I have configured my axios like this

const axiosConfig = {   baseURL: 'http://127.0.0.1:8000/api',   timeout: 30000, };  Vue.prototype.$axios = axios.create(axiosConfig) 

Inside my component, I make a call as

this.$axios.get('items').then().. 

Now the above works but I would like to change the baseURL without affecting the global base URL so that in my component I can simply use it without API endpoint so

I've tried

this.$axios.baseURL = "http://127.0.0.1:8000"; this.$axios.get().. //this is still in api endpoint 

How do I go about this?

like image 965
Geoff Avatar asked Nov 21 '17 07:11

Geoff


People also ask

What is Axios default base URL?

Global axios defaults axios. defaults. baseURL = 'https://api.example.com'; axios.

How do I set the default header in Axios?

Instead of adding the headers to each request, you can put them as default headers, and they will apply to all the requests. To do so, use the defaults. headers property of the axios object. This snippet will add the x-rapidapi-key header to all the requests.

What are Axios withCredentials?

The XMLHttpRequest. withCredentials property is a boolean value that indicates whether or not cross-site Access-Control requests should be made using credentials such as cookies, authorization headers or TLS client certificates. Setting withCredentials has no effect on same-site requests.

How do I get baseURL from Axios?

baseURL = 'https://api.example.com'; axios base url. axios default baseurl.


2 Answers

Instead of

this.$axios.get('items') 

use

this.$axios({ url: 'items', baseURL: 'http://new-url.com' }) 

If you don't pass method: 'XXX' then by default, it will send via get method.

Request Config: https://github.com/axios/axios#request-config

like image 180
Vipin Kumar Avatar answered Sep 17 '22 16:09

Vipin Kumar


Putting my two cents here. I wanted to do the same without hardcoding the URL for my specific request. So i came up with this solution.

To append 'api' to my baseURL, I have my default baseURL set as,

axios.defaults.baseURL = '/api/'; 

Then in my specific request, after explicitly setting the method and url, i set the baseURL to '/'

axios({     method:'post',     url:'logout',     baseURL: '/',    })    .then(response => {       window.location.reload();    })    .catch(error => {        console.log(error);    }); 
like image 31
shazyriver Avatar answered Sep 20 '22 16:09

shazyriver