整理一個基於axios請求封裝
首先是request.js,這個文件是用來處理axios的配置、設置攔截器等等,它創建了一個實例,並將這個實例導出。代碼如下.
import Vue from 'vue'
import axios from 'axios'
// 創建 axios 實例
const service = axios.create({
baseURL: '/user', // 基礎地址
timeout: 6000 // 請求超時時間
})
/**
* 請求攔截器,攜帶每個請求的token(可選)
*/
service.interceptors.request.use(config => {
const token = Vue.ls.get("ACCESS_TOKEN") //token是放在vuex中的state中
if (token) {
config.headers['X-Access-Token'] = token // 讓每個請求攜帶自定義 token 請根據實際情況自行修改
}
if (config.method == 'get') {
config.params = {
_t: Date.parse(new Date()) / 1000, //讓每個請求都攜帶一個不同的時間參數,防止瀏覽器緩存不發送請求
...config.params
}
}
return config
}, (error) => {
return Promise.reject(error)
})
/**
* 響應攔截器中的error錯誤處理
*/
const err = (error) => {
if (error.response) {
switch (error.response.status) {
case 401:
console.log({
message: '系統提示',
description: '未授權,請重新登錄',
duration: 4
})
break
case 403:
console.log({
message: '系統提示',
description: '拒絕訪問'
})
break
case 404:
console.log({
message: '系統提示',
description: '很抱歉,資源未找到!',
duration: 4
})
break
case 500:
console.log({
message: '系統提示',
description: 'Token失效,請重新登錄!'
})
break
case 504:
console.log({
message: '系統提示',
description: '網絡超時'
})
break
default:
console.log({
message: '系統提示',
description: error.response.data.message,
})
break
}
}
return Promise.reject(error)
};
/**
* 響應攔截器,將響應中的token取出,放到state中
*/
service.interceptors.response.use((response) => {
const token = response.headers["authorization"]
if (token) {
Vue.ls.set("ACCESS_TOKEN", token) //token是放在vuex中的state中
}
return response.data
}, err)
export {
service as axios
}
第二個便是manage.js,這個文件主要是書寫不同的http請求,get、post等,在請求中配置某些特殊的配置
import { axios } from './request'
//get
export function getAction(url,params) {
return axios({
url: url,
method: 'get',
params: params
})
}
//post
export function postAction(url,data) {
return axios({
url: url,
method:'post' ,
data: data
})
}
//put
export function putAction(url,data) {
return axios({
url: url,
method:'put',
data: data
})
}
//deleteAction
export function deleteAction(url,params) {
return axios({
url: url,
method: 'delete',
params: params
})
}
/**
* 下載文件
* @param {*} url: 請求地址
* @param {*} params: 請求參數
*/
export function downFileAction(url,params){
return axios({
url: url,
params: params,
method:'get' ,
responseType: 'blob'
})
}
/**
* 用於上傳文件
* @param {*} url:請求地址
* @param {*} data:請求體數據
*/
export function fileUploadAction(url,data){
return axios({
url: url,
data: data,
method:'post' ,
headers:{
'Content-Type':'multipart/form-data'
},
timeout:1000*60*4 //上傳時間4分鐘
})
}
最後這個api.js文件就是我們需要寫的接口了,把接口都寫在一個文件中,也是爲了方便我們維護,在使用的時候,導入使用便可
import { getAction,deleteAction,putAction,postAction,downFileAction,fileUploadAction} from '@/api/manage'
const getTest = (params)=>getAction("/api/user/get",params);
const deleteActionTest = (params)=>deleteAction("/api/user/delete",params);
const putActionTest = (params)=>putAction("/api/user/put",params);
const postActionTest = (params)=>postAction("/api/user/post",params);
const downFileActionTest = (params)=>downFileAction("/api/user/downfile",params);
const fileUploadActionTest = (params)=>fileUploadAction("/api/user/fileupload",params);
export {
getTest,
deleteActionTest,
putActionTest,
postActionTest,
downFileActionTest,
fileUploadActionTest
}
附帶一個項目中用到的文件下載鏈接處理
axios.get("/api/excel",{id:'001'}).then(res=>{//返回的數據是二進制文件流
var blob = new Blob([res],{type: 'application/force-download;charset=utf-8'});
var downloadElement = document.createElement('a');
var href = window.URL.createObjectURL(blob); //創建下載的鏈接
downloadElement.href = href;
downloadElement.download = 'name.xls'; //下載後文件名
document.body.appendChild(downloadElement);
downloadElement.click(); //點擊下載
document.body.removeChild(downloadElement); //下載完成移除元素
window.URL.revokeObjectURL(href); //釋放掉blob對象
})