Axios 是一個基於 promise 的HTTP 庫, 可以用在瀏覽器和 node.js 中。
1. 從瀏覽器創建 XMLHttpRequests
2. 從node.js 創建 http 請求
3. 支持Promise API
4. 攔截請求和響應
5. 轉換請求數據 和 響應數據
6. 取消請求
7. 自動轉換 JSON 數據
8. 客戶端支持防御 XSRF
<script type="text/javascript" src="node_modules/vue/dist/vue.js"></script> <script type="text/javascript" src="node_modules/axios/dist/axios.js"></script>
使用前將 axios ,添加到 Vue的父類 對象中。 以保證 Vue對象下掛載的所有的組件, 都可以訪問到 axios
Vue.prototype.$axios = axios;
// 給Vue的父類 prototype(原型) 掛載了一個 $axios, 這個$axios 執向的就是 axios
// 然后因為所有的組件 都是 掛載到 Vue中的。就可以通過 this.$axios 拿到 axios 這個對象。
為 axios 配置一些默認值:
axios.defaults.baseURL = 'http://127.0.0.1:8888';
// 配置公共的 url. 這樣在進行url 的請求時。 就不用每次都去寫,前面這些 協議 ip 端口,一類的信息。
// 他會自動的進行, 拼接,然后訪問
axios 的 get 請求
// 為給定 ID 的user 創建請求 axios 實在promise 的基礎上做的封裝
axios.get('/user?ID=12345') .then(function. (response){ console.log(response) }) .catch(function, (error){ console.log(error) })
對比 jquery 的代碼,其實都是一個流程: jquery是基於es5的基礎上 從http庫中,做的封裝
$.ajax({ url:"/user?ID=12345", type:"GET", success:function(response){
//成功返回的數據 }, error:fucntion(error_data){
//返回的錯誤 } })
axios 的post請求
sendAjaxByPost(){ // post 第二個參數是 要發送的數據, 這里可以提交任何的類型數據。 這要看后端要接受什么樣的數據 // 如果想要發送一個對象到 后端, 需要使用 URLSearchParams() 對數據,進行處理。 var params = new URLSearchParams(); // 使用這個對象去處理 params.append('name',"alex111"); // 在Vue中使用es5的function 函數。 this的指向會指向到Window對象。 // 解決辦法就是在進入這個函數之前, 講this用另外的變量保存起來。 然后在函數內部使用這個變量,所代表的this
//var _this = this; // 把外層的this 賦值給 _this //this.$axios.post('/create', params).then(function (res){_this.datas = res.data}).catch((error)=>{}); // 另一種方式就是,在vue中 如果要使用函數的話,盡量使用 => 箭頭函數。 這樣能保證this的執向, // 一直都是指向當前的這個Vue 實例對象, 不會亂跑。 this.$axios.post('/create', params).then((res)=>{this.datas = res.data}).catch((error)=>{}) },