request.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /**
  2. * @Description:request 封装
  3. * @Version: 1.0.0
  4. * @author:苏园园
  5. * @Date: 2024-3-29 15:42:41
  6. */
  7. import config from './config.js'
  8. class Request {
  9. http(param) {
  10. let url = param.url,
  11. header = param.header,
  12. method = param.method,
  13. data = param.data,
  14. dataType = 'json',
  15. responseType = param.responseType || 'text'
  16. if (header) {
  17. header = param.header
  18. } else {
  19. header = {
  20. 'Content-type': "application/x-www-form-urlencoded",
  21. };
  22. }
  23. const token = uni.getStorageSync('token');
  24. header['Authorization'] = header['Authorization'] ? header['Authorization'] : token;
  25. // 返回promise
  26. return new Promise((resolve, reject) => {
  27. // 请求
  28. uni.request({
  29. url: config.baseUrl + url,
  30. data: data,
  31. method: method,
  32. dataType: dataType,
  33. responseType: responseType,
  34. header: header,
  35. success: (res) => {
  36. if (res.statusCode && res.statusCode != 200) {
  37. uni.$u.toast("api错误" + res.data.error)
  38. return;
  39. }
  40. if (res.data.code !== 200) {
  41. // code判断:200成功,不等于200错误
  42. if (res.data.code == 501) {
  43. webUni.webView.reLaunch({
  44. url: "/pages/index/login/login",
  45. });
  46. } else if (res.data.code == 400 && res.data.msg == '登录凭证不为空') {
  47. uni.$u.toast('请登录小程序~');
  48. setTimeout(() => {
  49. webUni.webView.reLaunch({
  50. url: "/pages/index/login/login",
  51. });
  52. }, 500)
  53. } else {
  54. uni.$u.toast(res.data.msg)
  55. }
  56. }
  57. // 将结果抛出
  58. resolve(res.data)
  59. },
  60. //请求失败
  61. fail: (e) => {
  62. uni.$u.toast('网络异常, 请检查网络连接')
  63. resolve(e.data);
  64. },
  65. //请求完成
  66. complete() {
  67. resolve();
  68. return;
  69. },
  70. })
  71. })
  72. }
  73. }
  74. export default new Request()