request.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import configService from './baseurl.js'
  2. import { msg as toast, showConfirm, tansParams } from './common.js'
  3. import { getToken } from './auth.js'
  4. import errorCode from './errorCode.js'
  5. // 联调时调整:
  6. // 1.configService 的url
  7. // 2.请求头headers
  8. // 3.返回数据格式
  9. const BASE_URL = configService.apiUrl;
  10. let timeout = 10000
  11. const request = config => {
  12. const isToken = (config.headers || {}).isToken === false;
  13. config.headers = config.headers || {};
  14. if (getToken() && !isToken) {
  15. config.headers['Authorization'] = 'Bearer ' + getToken();
  16. }
  17. if (config.params) {
  18. let url = config.url + '?' + tansParams(config.params);
  19. url = url.slice(0, -1); // 去掉最后一个&
  20. config.url = url;
  21. }
  22. return new Promise((resolve, reject) => {
  23. uni.request({
  24. method: config.method || 'get',
  25. timeout: config.timeout || timeout,
  26. url: config.baseUrl || BASE_URL + config.url,
  27. data: config.data,
  28. header: config.headers,
  29. dataType: 'json'
  30. }).then(res => {
  31. const code = res.data.code || 200;
  32. const msg = errorCode[code] || res.data.msg || errorCode['default'];
  33. if (code === 401) {
  34. showConfirm('登录状态已过期,您可以继续留在该页面,或者重新登录?').then(res => {
  35. if (res.confirm) {
  36. uni.reLaunch({
  37. url: '/pages/login/login'
  38. });
  39. }
  40. });
  41. reject('无效的会话,或者会话已过期,请重新登录。');
  42. } else if (code === 500) {
  43. toast(msg);
  44. reject('500');
  45. } else if (code !== 200) {
  46. toast(msg);
  47. reject(code);
  48. }
  49. resolve(res.data.data);
  50. })
  51. .catch(error => {
  52. let {
  53. message
  54. } = error;
  55. if (message === 'Network Error') {
  56. message = '后端接口连接异常';
  57. } else if (message.includes('timeout')) {
  58. message = '系统接口请求超时';
  59. } else if (message.includes('Request failed with status code')) {
  60. message = '系统接口' + message.substr(message.length - 3) + '异常';
  61. }
  62. toast(message);
  63. reject(message);
  64. });
  65. });
  66. };
  67. export default request;