axios基础封装
import axios from "axios";
import {Message,MessageBox} from 'element-ui';
import store from '../store';
import {getToken} from 'utils/auth';
// 创建axios实例
const service = axios.create({
//可以不设置baseURL直接走proxy代理的地址 也可以设置全局参数
//baseURL: process.env.BASE_API, // api的base_url
timeout: 50000, // 请求超时时间
});
service.interceptors.request.use(
config => {
if (getToken()) {
// 让每个请求携带token--['access-token']为自定义key 请根据实际情况自行修改
config.headers["access-token"] = getToken();
}
return config;
},
error => {
// do something with request error
console.log(error); // for debug
return Promise.reject(error);
}
);
// respone拦截器 处理状态码
service.interceptors.response.use( response => {
/**
* 下面的注释为通过response自定义code来标示请求状态,当code返回如下情况为权限有问题
* 如通过xmlhttprequest 状态码标识 逻辑可写在下面error中
*/
const res = response.data;
if (res.status === 40301) {
Message.closeAll();
Message({
message: '登录超时,请重新登录!',
type: 'error',
duration: 5 * 1000
});
return Promise.reject('error');
}
if (res.status === 500) {
Message.closeAll();
Message({
message: '登录超时,请稍后重试!',
type: 'error',
duration: 5 * 1000
});
return Promise.reject('error');
}
if (res.status === 503) {
Message.closeAll();
Message({
message: '登录过期,请刷新后重试!',
type: 'error',
duration: 5 * 1000
});
return Promise.reject('error');
}
if (res.status === 504) {
Message.closeAll();
Message({
message: '连接服务器失败,请稍后重试!',
type: 'error',
duration: 5 * 1000
});
return Promise.reject('error');
}
if (res.status === 40001) {
Message.closeAll();
Message({
message: '服务异常!',
type: 'warning'
});
return Promise.reject('error');
}
if (response.status !== 200 && res.status !== 200) {
Message.closeAll();
Message({
message: res.message,
type: 'error',
duration: 5 * 1000
});
} else {
const data = response.data;
try {
if (data && data.data) {
data.data = JSON.parse(data.data);
}
} catch (e) {
}
return data;
}
},
error => {
// console.log(error); // for debug
Message.closeAll();
Message({
message: error.message,
type: 'error',
duration: 5 * 1000
});
return Promise.reject(error);
}
);
export default service;
请求方式
import request from 'request.js';
export function getMenus(token) {
return request({
url: '/api/admin/user/front/menus',
method: 'get',
params: { token:token }
});
}
export function addObj(data) {
return request({
url: '/api/admin/config/add',
method: 'post',
data: data
});
}
//下载 responseType: 'blob'
export function certificateDownload(params) {
return request({
url: 'device/certificate/download',
responseType: 'blob',
method: 'GET',
params
})
}
getMenus(state.token).then(res => {
console.log(res);
})
下载请求
// application/vnd.openxmlformats-officedocument.spreadsheetml.sheet这里表示xlsx类型 默认txt
certificateDownload(temp).then(res => {
const blob = new Blob([res], { type: 'application/zip;charset=UTF-8' })
const downloadElement = document.createElement('a')
const href = window.URL.createObjectURL(blob) // 创建下载的链接
downloadElement.href = href
downloadElement.download = '证书文件' // 下载后文件名
document.body.appendChild(downloadElement)
downloadElement.click() // 点击下载
document.body.removeChild(downloadElement) // 下载完成移除元素
window.URL.revokeObjectURL(href) // 释放掉blob对象
})
axios二次封装
封装 get post请求
import request from "../utils/request"; // 引入axios创建的实例
import { pathConfig } from "../api/pathConfig";//统一存放接口地址
export function post(group, method, data, timeout = 5000) {
return request({
url: pathConfig[group][method],
method: "post",
timeout: timeout,
data
});
}
export function get(group, method, params) {
return request({
url: pathConfig[group][method],
method: "get",
params
});
}
封装下载图片
- 拿到图片的文件流通过window.URL.createObjectURL转换成图片的url地址在页面展示
export function downloadPhoto(group, method, params,callback) {
return request({
url: pathConfig[group][method],
method: "get",
responseType: "blob",
params
}).then(res=>{
let blob = new Blob([res.data]);
let imageUrl = window.URL.createObjectURL(blob);
callback(imageUrl, res.data);
});
}
封装下载文件
// 下载需要加上responseType: "blob",
export function downLoad(group, method, data,filename) {
return request({
url: pathConfig[group][method],
responseType: "blob",
method: "post",
data
}).then((data) => {
//const blob = new Blob([data], { type:''}) 可以指定type类型
const blob = new Blob([data])
const downloadElement = document.createElement('a')
const href = window.URL.createObjectURL(blob) // 创建下载的链接
downloadElement.href = href
downloadElement.download = '文件name' // 下载后文件名
document.body.appendChild(downloadElement)
downloadElement.click() // 点击下载
document.body.removeChild(downloadElement) // 下载完成移除元素
window.URL.revokeObjectURL(href) // 释放掉blob对象
}).catch((r) => {
console.error(r)
})
}
import Cookies from "js-cookie";
const TokenKey = "Admin-Token";
const userName = "User-Name";
export function getToken() {
return Cookies.get(TokenKey);
}
export function setToken(token) {
return Cookies.set(TokenKey, token);
}
export function removeToken() {
Cookies.remove(TokenKey);
}
全局使用方式 main.js引入
import {post, get, downloadFile, uploadFileRequest} from './utils/axios';
Vue.prototype.$post = post;
Vue.prototype.$get = get;
Vue.prototype.$downloadFile = downLoad;
export const pathConfig = {
user: {
login: "sys/user/login",
logout: "sys/user/logout",
getResource: "sys/menuList",
},
}
请求方式
this.$post("user", "login", { }).then(res => {
do something...
})