ajax.js 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import axios from 'axios'
  2. import qs from 'qs'
  3. import router from '../router'
  4. import { Message } from 'element-ui'
  5. const token = function (headers) {
  6. let JWT
  7. if (headers) {
  8. localStorage.setItem('JWT', headers.authorization)
  9. JWT = headers.authorization
  10. }
  11. return JWT ? JWT : localStorage.getItem('JWT') // eslint-disable-line
  12. }
  13. const Axios = axios.create({
  14. timeout: 60000,
  15. responseType: 'json',
  16. withCredentials: true,
  17. queryData: {},
  18. urlData: {},
  19. headers: {
  20. 'Content-Type': 'multipart/form-data',
  21. 'authorization': token()
  22. }
  23. })
  24. Axios.interceptors.request.use((config) => {
  25. config.headers.authorization = token()
  26. config.urlData = { ...config.urlData, org: 'MQ' }
  27. // 处理请求data,若为get请求,拼到url后面,若为post请求,直接添加到body中
  28. let urlData = qs.stringify(config.urlData)
  29. let queryData = qs.stringify(config.queryData)
  30. // 判断是通过斜杠传参
  31. if (config.url.indexOf(':') > -1) {
  32. if (typeof config.urlData === 'object') {
  33. config.url = Object.keys(config.urlData).reduce((url, k) => { // 此方法对每个元素进行处理
  34. const re = new RegExp(`:${k}(?!w)`, 'i')
  35. return url.replace(re, config.urlData[k])
  36. }, config.url)
  37. } else {
  38. config.url = config.url.slice(0, config.url.indexOf(':')) + urlData
  39. }
  40. }
  41. if (queryData) {
  42. config.url += '?' + queryData
  43. }
  44. let fm = new FormData()
  45. for (let k in config.data) {
  46. if (Array.isArray(config.data[k])) {
  47. config.data[k].forEach((v) => {
  48. fm.append(k, v)
  49. })
  50. } else {
  51. fm.append(k, config.data[k])
  52. }
  53. }
  54. config.data = fm
  55. return config
  56. }, (error) => {
  57. console.log(error)
  58. })
  59. const ajax = (...args) => {
  60. return new Promise((resolve, reject) => {
  61. Axios(...args).then(({ data, headers }) => {
  62. if (headers.authorization) {
  63. token(headers)
  64. }
  65. const { code, message, result } = data
  66. if (code === 200) {
  67. resolve(result)
  68. } else if (code === 401) {
  69. router.push({ name: 'login' })
  70. } else {
  71. Message({
  72. message: message,
  73. type: 'error'
  74. })
  75. reject(data)
  76. }
  77. }).catch(reject)
  78. })
  79. }
  80. export default ajax