物管理前端
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

88 lines
2.1 KiB

  1. var messageFn = (msg) => {
  2. layui.use('layer', function(){
  3. const layer = layui.layer;
  4. layer.msg(msg);
  5. });
  6. };
  7. const BASE_PREFIX = '/thing';
  8. // 创建实例
  9. const tokenArr = window.location.search.split('token=');
  10. const cacheToken = sessionStorage.getItem('v1@CacheToken');
  11. const tokenParsed = JSON.parse(cacheToken || '{}');
  12. const axiosInstance = axios.create({
  13. // 前缀
  14. baseURL: BASE_PREFIX,
  15. // 超时
  16. timeout: 1000 * 30,
  17. // 请求头
  18. headers: {
  19. 'Content-Type': 'application/json',
  20. 'token': tokenArr[1] || tokenParsed.token || window.iframeNodeToken || '',
  21. 'tenantCode': localStorage.getItem('v1@CacheTenantCode') || '',
  22. 'companyId': localStorage.getItem('v1@CacheTenantCode') || '',
  23. },
  24. });
  25. // 请求拦截器
  26. axiosInstance.interceptors.request.use(
  27. (config) => {
  28. // TODO 在这里可以加上想要在请求发送前处理的逻辑
  29. // TODO 比如 loading 等
  30. return config
  31. },
  32. (error) => {
  33. return Promise.reject(error)
  34. },
  35. );
  36. // 响应拦截器
  37. axiosInstance.interceptors.response.use(
  38. (response) => {
  39. if (response.status === 200)
  40. return response.data
  41. messageFn(response.status)
  42. return response
  43. },
  44. (error) => {
  45. console.log('error', error)
  46. const { response } = error
  47. if (response) {
  48. if (response.status === 401) {
  49. messageFn("未授权")
  50. window.createLoginDialog();
  51. } else {
  52. messageFn(response.status)
  53. }
  54. return Promise.reject(response.data)
  55. }
  56. messageFn('网络连接异常,请稍后再试!')
  57. return Promise.reject(error)
  58. },
  59. );
  60. var service = {
  61. get(url, data, config) {
  62. return axiosInstance.get(url, { params: data, ...config })
  63. },
  64. post(url, data, config) {
  65. return axiosInstance.post(url, data, config)
  66. },
  67. put(url, data, config) {
  68. return axiosInstance.put(url, data, config)
  69. },
  70. delete(url, data) {
  71. return axiosInstance.delete(url, { data })
  72. },
  73. upload: (url, file) =>
  74. axiosInstance.post(url, file, {
  75. headers: { 'Content-Type': 'multipart/form-data' },
  76. }),
  77. download: (url, data) => {
  78. window.location.href = `${BASE_PREFIX}/${url}?${formatJsonToUrlParams(data)}`
  79. },
  80. };