http_20190318175757.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. import axios from 'axios';
  2. import {
  3. Message
  4. } from 'element-ui';
  5. axios.defaults.timeout = 5000;
  6. axios.defaults.baseURL = process.env.BASE_API;
  7. //http request 拦截器
  8. axios.interceptors.request.use(
  9. config => {
  10. // const token = getCookie('名称');注意使用的时候需要引入cookie方法,推荐js-cookie
  11. config.data = JSON.stringify(config.data);
  12. config.headers = {
  13. 'Content-Type': 'application/x-www-form-urlencoded'
  14. }
  15. // if(token){
  16. // config.params = {'token':token}
  17. // }
  18. return config;
  19. },
  20. error => {
  21. return Promise.reject(err);
  22. }
  23. );
  24. //http response 拦截器
  25. axios.interceptors.response.use(
  26. response => {
  27. if (response.data.errCode == 2) {
  28. router.push({
  29. path: "/login",
  30. querry: {
  31. redirect: router.currentRoute.fullPath
  32. } //从哪个页面跳转
  33. })
  34. }
  35. return response;
  36. },
  37. error => {
  38. return Promise.reject(error)
  39. }
  40. )
  41. /**
  42. * 封装get方法
  43. * @param url
  44. * @param data
  45. * @returns {Promise}
  46. */
  47. export function fetch(url, params = {}) {
  48. return new Promise((resolve, reject) => {
  49. axios.get(url, {
  50. params: params
  51. })
  52. .then(response => {
  53. resolve(response.data);
  54. })
  55. .catch(err => {
  56. reject(err)
  57. })
  58. })
  59. }
  60. /**
  61. * 封装post请求
  62. * @param url
  63. * @param data
  64. * @returns {Promise}
  65. */
  66. export function post(url, data = {}) {
  67. return new Promise((resolve, reject) => {
  68. axios.post(url, data)
  69. .then(response => {
  70. resolve(response.data);
  71. }, err => {
  72. reject(err)
  73. })
  74. })
  75. }
  76. /**
  77. * 封装patch请求
  78. * @param url
  79. * @param data
  80. * @returns {Promise}
  81. */
  82. export function patch(url, data = {}) {
  83. return new Promise((resolve, reject) => {
  84. axios.patch(url, data)
  85. .then(response => {
  86. resolve(response.data);
  87. }, err => {
  88. reject(err)
  89. })
  90. })
  91. }
  92. /**
  93. * 封装put请求
  94. * @param url
  95. * @param data
  96. * @returns {Promise}
  97. */
  98. export function put(url, data = {}) {
  99. return new Promise((resolve, reject) => {
  100. axios.put(url, data)
  101. .then(response => {
  102. resolve(response.data);
  103. }, err => {
  104. reject(err)
  105. })
  106. })
  107. }