request.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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.code !== 200) {
  15. wx.showToast({
  16. title: res.data.msg
  17. })
  18. }
  19. if (res.data.code == 401) {
  20. uni.redirectTo({
  21. url: '/pages/login/index'
  22. });
  23. }
  24. resolve(res)
  25. },
  26. fail: function(err) {
  27. uni.showToast({
  28. title: "请求接口失败!"
  29. })
  30. reject(err)
  31. }
  32. });
  33. })
  34. }
  35. const get = async ({ url, data, header }) => {
  36. return await request({ url, method: 'get', data, header });
  37. }
  38. const post = async ({ url, data, header }) => {
  39. return await request({ url, method: 'post', data, header });
  40. }
  41. const put = async ({ url, data, header }) => {
  42. return await request({ url, method: 'put', data, header });
  43. }
  44. export default { get, post, put };