Javascript 更改 axios 的默认基本 url
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47407564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change the default base url for axios
提问by Geoff
I have configured my axios like this
我已经像这样配置了我的 axios
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 baseURLwithout affecting the global base URL so that in my component i can simply use without API endpoint so
现在上述工作,但我想在baseURL不影响全局基本 URL的情况下更改,以便在我的组件中,我可以在没有 API 端点的情况下简单地使用
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?
我该怎么做?
采纳答案by Vipin Kumar
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 getmethod.
如果您不通过,method: 'XXX'则默认情况下,它将通过get方法发送。
Request Config:https://github.com/axios/axios#request-config
回答by shazyriver
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.
把我的两分钱放在这里。我想在不为我的特定请求硬编码 URL 的情况下做同样的事情。所以我想出了这个解决方案。
To append 'api'to my baseURL, I have my default baseURL set as,
为了附加'api'到我的 baseURL,我将我的默认 baseURL 设置为,
axios.defaults.baseURL = '/api/';
Then in my specific request, after explicitly setting the method and url, i set the baseURL to '/'
然后在我的特定请求中,在明确设置方法和 url 后,我将 baseURL 设置为 '/'
axios({
method:'post',
url:'logout',
baseURL: '/',
})
.then(response => {
window.location.reload();
})
.catch(error => {
console.log(error);
});
This is tested and working solution in my project.
这是在我的项目中经过测试和工作的解决方案。
回答by Jonathan Batista
From axios docsyou have baseURLand url
从axios 文档你有baseURL和url
baseURLwill be prepended to urlwhen making requests. So you can define baseURLas http://127.0.0.1:8000and make your requests to /url
baseURL将url在提出请求时添加到。所以你可以定义baseURL为http://127.0.0.1:8000并提出你的请求/url
//
`url` is the server URL that will be used for the request
url: '/user',
// `baseURL` will be prepended to `url` unless `url` is absolute.
// It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
// to methods of that instance.
baseURL: 'https://some-domain.com/api/',

