api.js 1.9 KB

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