ajax.js 1.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import axios from 'axios'
  2. import { Message } from 'element-ui'
  3. import qs from 'qs'
  4. const Axios = axios.create({
  5. timeout: 60000,
  6. responseType: 'json',
  7. withCredentials: true,
  8. headers: {
  9. 'Content-Type': 'multipart/form-data'
  10. }
  11. })
  12. Axios.interceptors.request.use((config) => {
  13. // 处理请求data,若为get请求,拼到url后面,若为post请求,直接添加到body中
  14. let data = qs.stringify(config.data)
  15. if (config.method === 'get' || config.method === 'GET') {
  16. // 判断是通过斜杠传参还是通过query传参
  17. if (config.url.indexOf(':') > -1) {
  18. if (typeof config.data === 'object') {
  19. config.url = Object.keys(config.data).reduce((url, k) => { // 此方法对每个元素进行处理
  20. const re = new RegExp(`:${k}(?!w)`, 'i')
  21. return url.replace(re, config.data[k])
  22. }, config.url)
  23. } else {
  24. config.url = config.url.slice(0, config.url.indexOf(':')) + data
  25. }
  26. } else {
  27. if (data) {
  28. config.url += '?' + data
  29. }
  30. }
  31. }
  32. let fm = new FormData()
  33. for (let k in config.data) {
  34. if (Array.isArray(config.data[k])) {
  35. fm.append(k, ...config.data[k].map(v => `${k}=${encodeURIComponent(v)}`))
  36. } else {
  37. fm.append(k, config.data[k])
  38. }
  39. }
  40. config.data = fm
  41. return config
  42. }, (error) => {
  43. console.log(error)
  44. })
  45. Axios.interceptors.response.use((res) => {
  46. if (res.data.code === 200) {
  47. return res.data.result
  48. } else {
  49. Message({
  50. message: res.data.message,
  51. type: 'error'
  52. })
  53. return res.data
  54. }
  55. }, (error) => {
  56. console.log(error)
  57. })
  58. export default Axios