api.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import config from '../config.js';
  2. const getDomain = (uri, method, type) => {
  3. let serverUrl = config.serverUrl;
  4. let fileUrl = config.serverFile;
  5. if (type && type == 'file') return fileUrl + `/files` + uri;
  6. else return serverUrl + `/cxyy/api` + uri;
  7. };
  8. // 获取token
  9. const getToken = () => {
  10. try {
  11. const value = uni.getStorageSync('token');
  12. if (value) return value;
  13. } catch {}
  14. };
  15. export const requestBase = async (uri, method = 'GET', data, type) => {
  16. let baseUrl = getDomain(uri, method, type);
  17. let header = {};
  18. const token = uni.getStorageSync('token');
  19. if (token) header.token = token;
  20. return new Promise((resolve, reject) => {
  21. uni.request({
  22. url: baseUrl,
  23. method: method || 'GET',
  24. data: data || {},
  25. header,
  26. success: (res) => {
  27. resolve(res.data);
  28. },
  29. fail: (err) => {
  30. uni.showToast({
  31. title: '请求接口失败',
  32. icon: 'fail',
  33. });
  34. reject(err.data);
  35. },
  36. });
  37. });
  38. };
  39. export const requestApp = async (uri, method = 'GET', data, type) => {
  40. let baseUrl = getDomain(uri, method, type);
  41. let header = {};
  42. const token = uni.getStorageSync('token');
  43. if (token) header.token = token;
  44. return new Promise((resolve, reject) => {
  45. uni.request({
  46. url: baseUrl,
  47. method: method || 'GET',
  48. data: data || {},
  49. header,
  50. success: (res) => {
  51. resolve(res.data);
  52. },
  53. fail: (err) => {
  54. uni.showToast({
  55. title: '请求接口失败',
  56. icon: 'fail',
  57. });
  58. reject(err.data);
  59. },
  60. });
  61. });
  62. };
  63. export const requestFile = (uri, method, data, type) => {
  64. let baseUrl = getDomain(uri, method, type);
  65. return new Promise((resolve, reject) => {
  66. uni.uploadFile({
  67. url: baseUrl,
  68. filePath: data,
  69. name: method || 'file',
  70. formData: {},
  71. success: (res) => {
  72. let data = JSON.parse(res.data);
  73. if (data.errcode != '0') {
  74. return uni.showToast({
  75. title: data.errmsg,
  76. icon: 'error',
  77. });
  78. }
  79. resolve(data);
  80. },
  81. fail: (err) => {
  82. let data = JSON.parse(err.data);
  83. uni.showToast({
  84. title: '请求接口失败',
  85. icon: 'fail',
  86. });
  87. reject(data);
  88. },
  89. });
  90. });
  91. };