[英]Switching from vue-resource to axios
使用vue-resource,我們可以在main.js
設置根URL, main.js
所示:
Vue.http.options.root = 'http://localhost:3000/api'
我嘗試將其替換為:
axios.defaults.baseURL = 'http://localhost:3000/api';
Vue.prototype.$http = axios
但是,現在我的帖子調用不能按預期工作,並且Vue.http.post
會拋出錯誤。
這是如何實現的?
使用axios,可以創建另一個具有自定義配置的實例
var my_axios = axios.create({
baseURL: 'http://localhost:3000/api',
});
從這里可以使用my_axios
進行操作。 您可以將自定義axios實例原型化為Vue:
Vue.prototype.$http = my_axios
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.