axios基础封装

  • request.js
  1. import axios from "axios";
  2. import {Message,MessageBox} from 'element-ui';
  3. import store from '../store';
  4. import {getToken} from 'utils/auth';
  5. // 创建axios实例
  6. const service = axios.create({
  7. //可以不设置baseURL直接走proxy代理的地址 也可以设置全局参数
  8. //baseURL: process.env.BASE_API, // apibase_url
  9. timeout: 50000, // 请求超时时间
  10. });
  11. service.interceptors.request.use(
  12. config => {
  13. if (getToken()) {
  14. // 让每个请求携带token--['access-token']为自定义key 请根据实际情况自行修改
  15. config.headers["access-token"] = getToken();
  16. }
  17. return config;
  18. },
  19. error => {
  20. // do something with request error
  21. console.log(error); // for debug
  22. return Promise.reject(error);
  23. }
  24. );
  25. // respone拦截器 处理状态码
  26. service.interceptors.response.use( response => {
  27. /**
  28. * 下面的注释为通过response自定义code来标示请求状态,当code返回如下情况为权限有问题
  29. * 如通过xmlhttprequest 状态码标识 逻辑可写在下面error
  30. */
  31. const res = response.data;
  32. if (res.status === 40301) {
  33. Message.closeAll();
  34. Message({
  35. message: '登录超时,请重新登录!',
  36. type: 'error',
  37. duration: 5 * 1000
  38. });
  39. return Promise.reject('error');
  40. }
  41. if (res.status === 500) {
  42. Message.closeAll();
  43. Message({
  44. message: '登录超时,请稍后重试!',
  45. type: 'error',
  46. duration: 5 * 1000
  47. });
  48. return Promise.reject('error');
  49. }
  50. if (res.status === 503) {
  51. Message.closeAll();
  52. Message({
  53. message: '登录过期,请刷新后重试!',
  54. type: 'error',
  55. duration: 5 * 1000
  56. });
  57. return Promise.reject('error');
  58. }
  59. if (res.status === 504) {
  60. Message.closeAll();
  61. Message({
  62. message: '连接服务器失败,请稍后重试!',
  63. type: 'error',
  64. duration: 5 * 1000
  65. });
  66. return Promise.reject('error');
  67. }
  68. if (res.status === 40001) {
  69. Message.closeAll();
  70. Message({
  71. message: '服务异常!',
  72. type: 'warning'
  73. });
  74. return Promise.reject('error');
  75. }
  76. if (response.status !== 200 && res.status !== 200) {
  77. Message.closeAll();
  78. Message({
  79. message: res.message,
  80. type: 'error',
  81. duration: 5 * 1000
  82. });
  83. } else {
  84. const data = response.data;
  85. try {
  86. if (data && data.data) {
  87. data.data = JSON.parse(data.data);
  88. }
  89. } catch (e) {
  90. }
  91. return data;
  92. }
  93. },
  94. error => {
  95. // console.log(error); // for debug
  96. Message.closeAll();
  97. Message({
  98. message: error.message,
  99. type: 'error',
  100. duration: 5 * 1000
  101. });
  102. return Promise.reject(error);
  103. }
  104. );
  105. export default service;

请求方式

  1. import request from 'request.js';
  2. export function getMenus(token) {
  3. return request({
  4. url: '/api/admin/user/front/menus',
  5. method: 'get',
  6. params: { token:token }
  7. });
  8. }
  9. export function addObj(data) {
  10. return request({
  11. url: '/api/admin/config/add',
  12. method: 'post',
  13. data: data
  14. });
  15. }
  16. //下载 responseType: 'blob'
  17. export function certificateDownload(params) {
  18. return request({
  19. url: 'device/certificate/download',
  20. responseType: 'blob',
  21. method: 'GET',
  22. params
  23. })
  24. }
  • 使用请求方式
  1. getMenus(state.token).then(res => {
  2. console.log(res);
  3. })

下载请求

  1. // application/vnd.openxmlformats-officedocument.spreadsheetml.sheet这里表示xlsx类型 默认txt
  2. certificateDownload(temp).then(res => {
  3. const blob = new Blob([res], { type: 'application/zip;charset=UTF-8' })
  4. const downloadElement = document.createElement('a')
  5. const href = window.URL.createObjectURL(blob) // 创建下载的链接
  6. downloadElement.href = href
  7. downloadElement.download = '证书文件' // 下载后文件名
  8. document.body.appendChild(downloadElement)
  9. downloadElement.click() // 点击下载
  10. document.body.removeChild(downloadElement) // 下载完成移除元素
  11. window.URL.revokeObjectURL(href) // 释放掉blob对象
  12. })

axios二次封装

封装 get post请求

  1. import request from "../utils/request"; // 引入axios创建的实例
  2. import { pathConfig } from "../api/pathConfig";//统一存放接口地址
  3. export function post(group, method, data, timeout = 5000) {
  4. return request({
  5. url: pathConfig[group][method],
  6. method: "post",
  7. timeout: timeout,
  8. data
  9. });
  10. }
  11. export function get(group, method, params) {
  12. return request({
  13. url: pathConfig[group][method],
  14. method: "get",
  15. params
  16. });
  17. }

封装下载图片

  • 拿到图片的文件流通过window.URL.createObjectURL转换成图片的url地址在页面展示
  1. export function downloadPhoto(group, method, params,callback) {
  2. return request({
  3. url: pathConfig[group][method],
  4. method: "get",
  5. responseType: "blob",
  6. params
  7. }).then(res=>{
  8. let blob = new Blob([res.data]);
  9. let imageUrl = window.URL.createObjectURL(blob);
  10. callback(imageUrl, res.data);
  11. });
  12. }

封装下载文件

  1. // 下载需要加上responseType: "blob",
  2. export function downLoad(group, method, data,filename) {
  3. return request({
  4. url: pathConfig[group][method],
  5. responseType: "blob",
  6. method: "post",
  7. data
  8. }).then((data) => {
  9. //const blob = new Blob([data], { type:''}) 可以指定type类型
  10. const blob = new Blob([data])
  11. const downloadElement = document.createElement('a')
  12. const href = window.URL.createObjectURL(blob) // 创建下载的链接
  13. downloadElement.href = href
  14. downloadElement.download = '文件name' // 下载后文件名
  15. document.body.appendChild(downloadElement)
  16. downloadElement.click() // 点击下载
  17. document.body.removeChild(downloadElement) // 下载完成移除元素
  18. window.URL.revokeObjectURL(href) // 释放掉blob对象
  19. }).catch((r) => {
  20. console.error(r)
  21. })
  22. }
  • anth.js
  1. import Cookies from "js-cookie";
  2. const TokenKey = "Admin-Token";
  3. const userName = "User-Name";
  4. export function getToken() {
  5. return Cookies.get(TokenKey);
  6. }
  7. export function setToken(token) {
  8. return Cookies.set(TokenKey, token);
  9. }
  10. export function removeToken() {
  11. Cookies.remove(TokenKey);
  12. }

全局使用方式 main.js引入

  1. import {post, get, downloadFile, uploadFileRequest} from './utils/axios';
  2. Vue.prototype.$post = post;
  3. Vue.prototype.$get = get;
  4. Vue.prototype.$downloadFile = downLoad;
  • pathConfig.js
  1. export const pathConfig = {
  2. user: {
  3. login: "sys/user/login",
  4. logout: "sys/user/logout",
  5. getResource: "sys/menuList",
  6. },
  7. }

请求方式

  1. this.$post("user", "login", { }).then(res => {
  2. do something...
  3. })