request.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. import axios from 'axios';
  2. import qs from 'qs';
  3. import { Message } from 'element-ui';
  4. import store from '@/store';
  5. import { getToken, setToken } from '@/utils/auth';
  6. /**
  7. * 设置全局参数
  8. */
  9. axios.defaults.baseURL = process.env.VUE_APP_BASE_API;
  10. // axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
  11. // axios.defaults.withCredentials = true
  12. axios.defaults.timeout = process.env.VUE_APP_API_TIMEOUT;
  13. // create an axios instance
  14. const service = axios.create({
  15. baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  16. // withCredentials: true, // send cookies when cross-domain requests
  17. timeout: 5000 // request timeout
  18. });
  19. // request interceptor
  20. axios.interceptors.request.use(
  21. config => {
  22. // do something before request is sent
  23. if (store.getters.token) {
  24. // let each request carry token
  25. // ['X-Token'] is a custom headers key
  26. // please modify it according to the actual situation
  27. config.headers['token'] = getToken();
  28. }
  29. return config;
  30. },
  31. error => {
  32. // do something with request error
  33. console.log(error); // for debug
  34. return Promise.reject(error);
  35. }
  36. );
  37. // response interceptor
  38. axios.interceptors.response.use(
  39. /**
  40. * If you want to get http information such as headers or status
  41. * Please return response => response
  42. */
  43. response => {
  44. const res = response.data;
  45. if (res.code === 401) {
  46. setToken();
  47. // 045 登录态失效,重定向到登录页 更改地址
  48. location.replace(`https://youxiangle.cn/yxl-admin/#/login`);
  49. Message({
  50. message: 'Token失效,请重新登陆',
  51. type: 'error',
  52. duration: 5 * 1000
  53. });
  54. return Promise.reject(new Error(''));
  55. }
  56. return res;
  57. },
  58. error => {
  59. console.log('错误 response', error);
  60. return Promise.reject(error);
  61. }
  62. );
  63. // 预处理配置文件
  64. const pretreatConfig = _config => {
  65. if (_config && 'dataType' in _config) {
  66. if (_config.dataType === 'json') {
  67. Object.assign(_config, {
  68. headers: {
  69. 'Content-Type': 'application/json;charset=UTF-8'
  70. }
  71. });
  72. } else if (_config.dataType === 'formdata') {
  73. Object.assign(_config, {
  74. headers: {
  75. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  76. }
  77. });
  78. }
  79. }
  80. if (
  81. process.env.NODE_ENV !== 'production' &&
  82. _config &&
  83. 'mock' in _config &&
  84. _config.mock
  85. ) {
  86. Object.assign(_config, {
  87. baseURL: process.env.VUE_APP_BASE_API_MOCK
  88. });
  89. }
  90. return _config;
  91. };
  92. /**
  93. * 处理response
  94. * @param {axios请求结果} fetchResult
  95. */
  96. const formatResponse = fetchResult =>
  97. fetchResult
  98. .then(response => formatStatus(response))
  99. .then(res => formatCode(res), handleNetworkError);
  100. /**
  101. * 格式化status
  102. */
  103. const formatStatus = response => {
  104. // 如果http状态码正常,则直接返回数据
  105. if (response && response.code === 200) {
  106. response.success = true;
  107. return response;
  108. // 如果不需要除了data之外的数据,可以直接 return response.data
  109. }
  110. // console.warn('---------------2-----------------')
  111. // console.warn(response)
  112. let txt = '网络异常';
  113. if (!response) {
  114. txt = '通信错误';
  115. } else if (response.code === 500) {
  116. txt = response.msg || '服务器错误';
  117. // } else if (response.code === 401) {
  118. // txt = '身份验证失败'
  119. } else if (response.code === 100000) {
  120. txt = response.msg || '服务器错误';
  121. }
  122. Message({
  123. message: txt || 'Error',
  124. type: 'error',
  125. duration: 5 * 1000
  126. });
  127. // 异常状态下,把错误信息返回去
  128. return {
  129. code: -404,
  130. msg: txt,
  131. request: response.request || {}
  132. };
  133. };
  134. /**
  135. * 格式化code
  136. */
  137. const formatCode = ({ code, data, msg }) => {
  138. // 如果code异常(这里已经包括网络错误,服务器错误,后端抛出的错误),可以弹出一个错误提示,告诉用户
  139. if (code === -404) {
  140. return {
  141. code: code,
  142. success: false,
  143. msg,
  144. data: {}
  145. };
  146. }
  147. // // api内置错误类型
  148. // if (data && !data.success) {
  149. // let msg = data.msg
  150. // if (data.code === 500) {
  151. // msg = '内部服务器错误'
  152. // }
  153. // return {
  154. // success: false,
  155. // msg,
  156. // code: data.code,
  157. // errorObj: data.error,
  158. // data: {}
  159. // }
  160. // }
  161. return {
  162. success: code === 200,
  163. msg,
  164. code,
  165. data
  166. };
  167. };
  168. // 处理网络通信错误
  169. const handleNetworkError = error => {
  170. if (error) {
  171. if (error.response && error.response.status === 500) {
  172. return {
  173. code: 500,
  174. success: false,
  175. msg: '通信错误',
  176. data: {}
  177. };
  178. } else if (error.response && error.response.status === 401) {
  179. store.dispatch('user/resetToken');
  180. setToken();
  181. // location.replace(`http://wxhd.lifespaceprobiotics.cn/code/admin/#/login`);
  182. }
  183. if (error.message.includes('timeout')) {
  184. return {
  185. code: 1,
  186. success: false,
  187. msg: '通信超时',
  188. data: {}
  189. };
  190. // } if (error.msg.includes('404')) {
  191. // return {
  192. // code: 1,
  193. // success: false,
  194. // msg: '通信失败',
  195. // data: {}
  196. // }
  197. }
  198. }
  199. return {
  200. code: -1,
  201. success: false,
  202. msg: '',
  203. data: {}
  204. };
  205. };
  206. /* 暂时不需要下载 要调整 */
  207. // const formatDownload = (fetchResult, name = '压缩文件') => fetchResult
  208. // .then(response => {
  209. // const filename = `${name}.zip`
  210. // const blob = response
  211. // if (typeof window.navigator.msSaveBlob !== 'undefined') {
  212. // // IE workaround for "HTML7007: One or more blob URLs were
  213. // // revoked by closing the blob for which they were created.
  214. // // These URLs will no longer resolve as the data backing
  215. // // the URL has been freed."
  216. // window.navigator.msSaveBlob(blob, filename)
  217. // } else {
  218. // const blobURL = window.URL.createObjectURL(blob)
  219. // const tempLink = document.createElement('a')
  220. // tempLink.style.display = 'none'
  221. // tempLink.href = blobURL
  222. // tempLink.setAttribute('download', filename)
  223. // // Safari thinks _blank anchor are pop ups. We only want to set _blank
  224. // // target if the browser does not support the HTML5 download attribute.
  225. // // This allows you to download files in desktop safari if pop up blocking
  226. // // is enabled.
  227. // if (typeof tempLink.download === 'undefined') {
  228. // tempLink.setAttribute('target', '_blank')
  229. // }
  230. // document.body.appendChild(tempLink)
  231. // tempLink.click()
  232. // document.body.removeChild(tempLink)
  233. // window.URL.revokeObjectURL(blobURL)
  234. // }
  235. // // Message({
  236. // // message: '请求下载文件失败,请稍后重试~',
  237. // // type: 'error',
  238. // // duration: 5 * 1000
  239. // // })
  240. // // }
  241. // })
  242. const get = (url, data = {}, config) => {
  243. config = pretreatConfig(config);
  244. return formatResponse(
  245. axios.get(url, {
  246. ...config,
  247. params: data,
  248. paramsSerializer(params) {
  249. return qs.stringify(params, {
  250. arrayFormat: 'brackets'
  251. });
  252. }
  253. })
  254. );
  255. };
  256. const del = (url, data = {}, config, type) => {
  257. config = pretreatConfig(config);
  258. return formatResponse(
  259. axios.delete(url, {
  260. ...config,
  261. params: data,
  262. paramsSerializer(params) {
  263. return qs.stringify(params, {
  264. arrayFormat: 'brackets'
  265. });
  266. }
  267. })
  268. );
  269. };
  270. const delData = (url, data = {}, params, config) => {
  271. config = pretreatConfig(config);
  272. return formatResponse(
  273. axios.delete(url, {
  274. ...config,
  275. data: data,
  276. params: params,
  277. paramsSerializer(params) {
  278. return qs.stringify(params, {
  279. arrayFormat: 'brackets'
  280. });
  281. }
  282. })
  283. );
  284. };
  285. const post = (url, data = {}, config) => {
  286. config = pretreatConfig(config);
  287. config = Object.assign(
  288. {
  289. headers: {
  290. 'Content-Type': 'application/json; charset=UTF-8'
  291. }
  292. },
  293. config
  294. );
  295. return formatResponse(
  296. axios.post(
  297. url,
  298. {
  299. data,
  300. seq: config.seq,
  301. token: config.token,
  302. limit: data.limit,
  303. start: data.start
  304. },
  305. config
  306. )
  307. );
  308. };
  309. const postData = (url, data = {}, config) => {
  310. config = pretreatConfig(config);
  311. config = Object.assign(
  312. {
  313. headers: {
  314. 'Content-Type': 'multipart/form-data; charset=UTF-8'
  315. }
  316. },
  317. config
  318. );
  319. return formatResponse(axios.post(url, data, config));
  320. };
  321. const put = (url, data = {}, config) => {
  322. config = pretreatConfig(config);
  323. config = Object.assign(
  324. {
  325. headers: {
  326. 'Content-Type': 'application/json; charset=UTF-8'
  327. }
  328. },
  329. config
  330. );
  331. return formatResponse(
  332. axios.put(url, { data, seq: config.seq, token: config.token }, config)
  333. );
  334. };
  335. /* 上方注释函数 */
  336. // export const download = (url, data = {}, config, name) => {
  337. // config = pretreatConfig(config)
  338. // config = Object.assign({
  339. // headers: {
  340. // 'Content-Type': 'application/json'F
  341. // },
  342. // responseType: 'blob'
  343. // }, config)
  344. // // return formatDownload(axios.post(url, data, config), name)
  345. // return formatDownload(axios.post(url, data, config), name)
  346. // }
  347. // export default axios;
  348. export default {
  349. get,
  350. post,
  351. postData,
  352. del,
  353. put,
  354. delData
  355. // download
  356. };