Axios 是一個基於 promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中
先看一個簡單示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div id="app"> </div> <script type="text/javascript" src="../vue.min.js"></script> <script src="../node_modules/axios/dist/axios.js"></script> <script type="text/javascript"> var App = { template: ` <div> <button @click = 'sendAjax'>發請求</button> </div> `, methods: { sendAjax() { this.$axios.get('http://127.0.0.1:8888/') .then(res => { console.log(res); }) .catch(err => { console.log(err); }) } } }; Vue.prototype.$axios = axios new Vue({ el: '#app', template: `<App />`, components: { App } }); </script> </body> </html>
合並請求
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div id="app"> </div> <script type="text/javascript" src="./vue.min.js"></script> <script src="./node_modules/axios/dist/axios.js"></script> <script type="text/javascript"> var App = { data() { return { res1: "", res2: '' } }, template: ` <div> 響應1:{{res1}} 響應2:{{res2}} <button @click = 'sendAjax'>合並請求</button> </div> `, methods: { sendAjax() { // 請求1 get: / // 請求2 post : /add this.$axios.defaults.baseURL = 'http://127.0.0.1:8888/'; var q1 = this.$axios.get(''); var q2 = this.$axios.post('add', 'a=1'); this.$axios.all([q1, q2]) .then(this.$axios.spread((res1, res2) => { // 全部成功了 this.res1 = res1.data; this.res2 = res2.data; })) .catch(err => { // 其一失敗 console.log(err); }) } } }; Vue.prototype.$axios = axios new Vue({ el: '#app', template: `<App />`, components: { App } }); </script> </body> </html>
可選項options
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div id="app"> </div> <script type="text/javascript" src="./vue.min.js"></script> <script src="./node_modules/axios/dist/axios.js"></script> <script type="text/javascript"> var App = { template: ` <div> <button @click = 'sendAjax'>發請求</button> </div> `, methods: { sendAjax() { this.$axios.defaults.baseURL = 'http://127.0.0.1:8888/' this.$axios.get('', { params: { id: 1 }, // 在傳遞給then/catch之前,允許修改響應的數據 transformResponse: [function(data) { // 對 data 進行任意轉換處理 // console.log(data); // console.log(typeof data); data = JSON.parse(data); console.log(data); return data; }] }) .then(res => { console.log(res.data.msg); }) .catch(err => { console.log(err); }) this.$axios.post('/add', { firstName: 'Fred' }, { // `transformRequest` 允許在向服務器發送前,修改請求數據 // 只能用在 'PUT', 'POST' 和 'PATCH' 這幾個請求方法 // 后面數組中的函數必須返回一個字符串,或 ArrayBuffer,或 Stream transformRequest: [function(data) { // 對 data 進行任意轉換處理 console.log(data); return data; }], }) .then(res => { console.log(res); }) .catch(err => { console.log(err); }) } } }; Vue.prototype.$axios = axios new Vue({ el: '#app', template: `<App />`, components: { App } }); </script> </body> </html>
一個上傳文件的示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div id="app"> </div> <script type="text/javascript" src="./vue.min.js"></script> <script src="./node_modules/axios/dist/axios.js"></script> <script type="text/javascript"> var App = { data() { return { file: {}, rate: 0 } }, template: ` <div> 上傳進度:{{rate}}% 選擇文件: <input type="file" name = 'file' @change = 'changeHandler'/> <button @click='sendAjax'>發送請求</button> </div> `, methods: { sendAjax() { this.$axios.defaults.baseURL = 'http://127.0.0.1:8888/'; var fd = new FormData(); fd.append('file', this.file); this.$axios.post('upload', fd, { onUploadProgress: (progressEvent) => { // 對原生進度事件的處理 console.log(progressEvent); var progress = (progressEvent.loaded / progressEvent.total) * 100; console.log(progress); this.$nextTick(function() { this.rate = Math.ceil(progress); }) } }) .then(res => { console.log(res); }) .catch(err => { console.log(err); }) }, changeHandler(e) { console.log(e.target.files[0]); this.file = e.target.files[0]; } } }; Vue.prototype.$axios = axios new Vue({ el: '#app', template: `<App />`, components: { App } }); </script> </body> </html>
一個取消請求的示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div id="app"> </div> <script type="text/javascript" src="./vue.min.js"></script> <script src="./node_modules/axios/dist/axios.js"></script> <script type="text/javascript"> var App = { data() { return { file: {}, rate: 0, source: null, currengtLoaded: 0 } }, template: ` <div> 上傳進度:{{rate}}% 選擇文件: <input type="file" name = 'file' @change = 'changeHandler'/> <button @click='sendAjax'>發送請求</button> <button @click = 'cancel'>取消請求</button> <button @click = 'resume'>續傳</button> </div> `, methods: { resume() { var fileData = this.file.slice(this.currengtLoaded, this.file.size); var fd = new FormData(); fd.append('file', fileData); this.$axios.defaults.baseURL = 'http://127.0.0.1:8888/'; var CancelToken = this.$axios.CancelToken; var source = CancelToken.source(); this.source = source; this.$axios.post('upload', fd, { // 攜帶取消標識 cancelToken: source.token, onUploadProgress: (progressEvent) => { // 對原生進度事件的處理 console.log(progressEvent); this.currengtLoaded += progressEvent.loaded; var progress = (this.currengtLoaded / progressEvent.total) * 100; console.log(progress); this.$nextTick(function() { this.rate = Math.ceil(progress); }) } }) .then(res => { console.log(res); }) .catch(err => { console.log(err); }) }, cancel() { this.source.cancel('請求被取消'); }, sendAjax() { this.$axios.defaults.baseURL = 'http://127.0.0.1:8888/'; var CancelToken = this.$axios.CancelToken; var source = CancelToken.source(); this.source = source; var fd = new FormData(); fd.append('file', this.file); this.$axios.post('upload', fd, { // 攜帶取消標識 cancelToken: source.token, onUploadProgress: (progressEvent) => { // 對原生進度事件的處理 console.log(progressEvent); this.currengtLoaded = progressEvent.loaded; var progress = (progressEvent.loaded / progressEvent.total) * 100; console.log(progress); this.$nextTick(function() { this.rate = Math.ceil(progress); }) } }) .then(res => { console.log(res); }) .catch(err => { console.log(err); }) }, changeHandler(e) { console.log(e.target.files[0]); this.file = e.target.files[0]; } } }; Vue.prototype.$axios = axios new Vue({ el: '#app', template: `<App />`, components: { App } }); </script> </body> </html>
一個攔截器的示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> .spinner { margin: 100px auto; width: 50px; height: 60px; text-align: center; font-size: 10px; } .spinner>div { background-color: #67CF22; height: 100%; width: 6px; display: inline-block; -webkit-animation: stretchdelay 1.2s infinite ease-in-out; animation: stretchdelay 1.2s infinite ease-in-out; } .spinner .rect2 { -webkit-animation-delay: -1.1s; animation-delay: -1.1s; } .spinner .rect3 { -webkit-animation-delay: -1.0s; animation-delay: -1.0s; } .spinner .rect4 { -webkit-animation-delay: -0.9s; animation-delay: -0.9s; } .spinner .rect5 { -webkit-animation-delay: -0.8s; animation-delay: -0.8s; } @-webkit-keyframes stretchdelay { 0%, 40%, 100% { -webkit-transform: scaleY(0.4) } 20% { -webkit-transform: scaleY(1.0) } } @keyframes stretchdelay { 0%, 40%, 100% { transform: scaleY(0.4); -webkit-transform: scaleY(0.4); } 20% { transform: scaleY(1.0); -webkit-transform: scaleY(1.0); } } </style> </head> <body> <div id="app"> </div> <script type="text/javascript" src="./vue.min.js"></script> <script src="./node_modules/axios/dist/axios.js"></script> <script type="text/javascript"> var App = { data() { return { isShow: false } }, template: ` <div> <div class="spinner" v-show = 'isShow'> <div class="rect1"></div> <div class="rect2"></div> <div class="rect3"></div> <div class="rect4"></div> <div class="rect5"></div> </div> <button @click = 'sendAjax'>發請求</button> </div> `, methods: { sendAjax() { // 添加請求攔截器 this.$axios.interceptors.request.use((config) => { console.log(config); // 在發送請求之前做些什么 var token = localStorage.getItem('token'); if (token) { config.headers['token'] = token; } this.isShow = true; return config; }, function(error) { // 對請求錯誤做些什么 return Promise.reject(error); }); // 添加響應攔截器 this.$axios.interceptors.response.use((response) => { // 對響應數據做點什么 console.log(response.data.token); if (response.data.token) { localStorage.setItem('token', response.data.token); } this.isShow = false; return response; }, function(error) { // 對響應錯誤做點什么 return Promise.reject(error); }); this.$axios.get('http://127.0.0.1:8888/') .then(res => { console.log(res); }) .catch(err => { console.log(err); }) } } }; Vue.prototype.$axios = axios new Vue({ el: '#app', template: `<App />`, components: { App } }); </script> </body> </html>