request.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import { BASE_URL } from '../env.js';
  2. const request = ({ url, method, data, header }) => {
  3. return new Promise((resolve, reject) => {
  4. const token = uni.getStorageSync('token');
  5. uni.request({
  6. url: url.includes('http') ? url : BASE_URL.url + url,
  7. method,
  8. data,
  9. header: {
  10. 'Authorization': url == '/login' ? '' : `Bearer ${token}`
  11. },
  12. dataType: 'json',
  13. success: function(res) {
  14. if (res.data.errcode && res.data.errcode != 0) {
  15. wx.showToast({
  16. title: res.data.details || '获取失败',
  17. icon: 'error'
  18. })
  19. }
  20. if (res.data.code && res.data.code !== 200) {
  21. wx.showToast({
  22. title: res.data.msg
  23. })
  24. }
  25. if (res.data.code && res.data.code == 401) {
  26. uni.redirectTo({
  27. url: '/pages/login/index'
  28. });
  29. }
  30. resolve(res)
  31. },
  32. fail: function(err) {
  33. uni.showToast({
  34. title: "请求接口失败!"
  35. })
  36. reject(err)
  37. }
  38. });
  39. })
  40. }
  41. const get = async ({ url, data, header }) => {
  42. return await request({ url, method: 'get', data, header });
  43. }
  44. const post = async ({ url, data, header }) => {
  45. return await request({ url, method: 'post', data, header });
  46. }
  47. const put = async ({ url, data, header }) => {
  48. return await request({ url, method: 'put', data, header });
  49. }
  50. const del = async ({ url, data, header }) => {
  51. return await request({ url, method: 'delete', data, header });
  52. }
  53. export default { get, post, put, del };