requests.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import axios from 'axios'
  2. import { Notification, MessageBox, Message } from 'element-ui'
  3. import store from '@/store'
  4. import { getToken } from '@/utils/auth'
  5. import errorCode from '@/utils/errorCode'
  6. import Cookies from "js-cookie";
  7. axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
  8. // 配置公共的根路径
  9. const services = axios.create({
  10. // 线上地址
  11. baseURL: 'http://172.4.5.232:12092',
  12. // 超时
  13. timeout: 10000
  14. })
  15. // 请求拦截器
  16. services.interceptors.request.use(config => {
  17. // 是否需要设置 token
  18. const isToken = (config.headers || {}).isToken === false
  19. if (getToken() && !isToken) {
  20. config.headers['Authorization'] = 'Bearer ' + Cookies.get("accessToken") // 让每个请求携带自定义token 请根据实际情况自行修改
  21. }
  22. // get请求映射params参数
  23. if (config.method === 'get' && config.params) {
  24. let url = config.url + '?';
  25. for (const propName of Object.keys(config.params)) {
  26. const value = config.params[propName];
  27. var part = encodeURIComponent(propName) + "=";
  28. if (value !== null && typeof (value) !== "undefined") {
  29. if (typeof value === 'object') {
  30. for (const key of Object.keys(value)) {
  31. if (value[key] !== null && typeof (value[key]) !== 'undefined') {
  32. let params = propName + '[' + key + ']';
  33. let subPart = encodeURIComponent(params) + '=';
  34. url += subPart + encodeURIComponent(value[key]) + '&';
  35. }
  36. }
  37. } else {
  38. url += part + encodeURIComponent(value) + "&";
  39. }
  40. }
  41. }
  42. url = url.slice(0, -1);
  43. config.params = {};
  44. config.url = url;
  45. }
  46. return config
  47. }, error => {
  48. console.log(error)
  49. Promise.reject(error)
  50. })
  51. export default services