使用vue-resource,我们可以在main.js中设置根url,如下所示:
Vue.http.options.root = 'http://localhost:3000/api'我尝试将其替换为:
axios.defaults.baseURL = 'http://localhost:3000/api';
Vue.prototype.$http = axios然而,现在我的post调用不能像预期的那样工作,并且Vue.http.post抛出一个错误。
这是如何实现的?
发布于 2017-01-27 16:23:42
使用axios,可以创建另一个实例having a custom config
var my_axios = axios.create({
baseURL: 'http://localhost:3000/api',
});从这里可以使用my_axios进行操作。您可以将自定义axios实例原型化为Vue:
Vue.prototype.$http = my_axios发布于 2017-04-30 12:58:39
import axios from 'axios';
export const HTTP = axios.create({
baseURL: `http://localhost:3000/api/`,
headers: {
Authorization: 'Bearer {token}'
}
})您现在可以像这样使用HTTP
<script>
import {HTTP} from './http-common';
export default {
data: () => ({
posts: [],
errors: []
}),
created() {
HTTP.get(`posts`)
.then(response => {
this.posts = response.data
})
.catch(e => {
this.errors.push(e)
})
}
}
</script>https://stackoverflow.com/questions/41879928
复制相似问题