什么是 axios
- axios 是一個基于 Promise 的,為瀏覽器和 Node.js 設(shè)計的 HTTP 客戶端宇攻。它盡可能簡化封裝了 HTTP 相關(guān)的各種操作叹哭,在 Web App 中使用非常方便晰绎。
- Vue 2 官方建議在由 Vue 構(gòu)建的 SPA 中使用 axios 進行 HTTP 操作彼硫。
- 傳送門:mzabriskie/axios
基本用法
-
初始化一個 axios 實例
const ajaxInstance = axios.create({ baseURL: url, timeout: 30000 // 30 seconds. });
-
GET .get(url, [conf])
ajaxInstance.get('/job/joblist', { params: { user: store.state.auth.username } }).then((response) => { if (response.status === 200) { return true; } else { console.log(response.status); return false; } }).catch((error) => { console.error(error); return false; });
-
POST Params .post(url, [data, [conf]])
ajaxInstance.post('/auth/userLogin', {}, { params: { username: user.username, password: user.password }, }).then((response) => { // if auth success. then -> console.log(response); // for test only console.log(response.data.Login; if((response.data.Login === 0)) { // login success return true; } else { return false; } }).catch((error) => { console.error(error); return false; });
-
POST JSON
ajaxInstance.post('/auth/userLogin', { username: '', password: '' }).then((response) => { // if auth success. then -> console.log(response); // for test only console.log(response.data.Login; if((response.data.Login === 0)) { // login success return true; } else { return false; } }).catch((error) => { console.error(error); return false; });
-
POST 表單( FormData )
let data = new FormData(); data.append('upload_file', file); data.append('path', store.state.dataPreview.path); data.append('user', store.state.auth.username); return ajaxInstance.post('/action/upload', data).then((response) => { if (response.data === 'success') { return true; } else { console.log(response.data); return false; } }).catch((error) => { console.error(error); return false; });
遇到的問題
- 如何在 SPA 中封裝 axios 以供組件使用:
首先吃溅,直接在組件中進行 HTTP Request 是不合理的溶诞,因為維護起來不方便,也不利于代碼復(fù)用决侈。
可以封裝一個全局
util
類螺垢,實例化一個 axios 對象,涉及與 axios 相關(guān)的操作的函數(shù)都放在這個類中赖歌,組件通過引用這個類并調(diào)用相關(guān)函數(shù)來發(fā)起 HTTP Request 枉圃。-
要注意的是,如果需要用到
Promise
的異步特性俏站,通過異步返回值控制視圖讯蒲,以實現(xiàn)友好的界面交互 / 提示(或者其他目的),一定要將整個 axios 返回(其實就是返回一個 Promise)肄扎,而不是只返回某個結(jié)果值(可以參考上述代碼中 POST 表單的部分)。然后再利用Promise
異步處理返回的結(jié)果即可赁酝。// util 中的 submit 函數(shù) const submitTask = (taskInfo, file) => { let data = new FormData(); data.append('job', JSON.stringify(taskInfo)); data.append('user', store.state.auth.username); data.append('job_file', file); return ajaxInstance.post('/job/start_job', data).then((response) => { console.log(response); if (response.data === 'success') { return true; } else { return false; } }).catch((error) => { console.error(error); return false; }); }
// submit 頁面 util.submitTask(taskInfo, this.newFile).then((res) => { if (res) { this.$Message.success('已提交犯祠。'); cleanSubmit(); } else { this.$Message.error('提交失敗。'); cleanSubmit(); }; })
- 如何提交表單:
- 提交表單時一定要使用
FromData
對象手動生成一個表單酌呆,并把FormData
當(dāng)做data
傳遞給 axios 衡载,axios 會自動識別data
的類型并設(shè)置好相應(yīng)的 Request Header 。提交文件只需要將文件對象append
到表單中即可隙袁。
- 提交表單時一定要使用