index.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // 服务器地址 开发环境 生产环境
  2. const REQUESTURL = {
  3. development: "http://192.168.2.164:8089",
  4. production: ""
  5. };
  6. // 请求数据拦截
  7. const REQUESTINTERCPTOR = function(request) {
  8. let _token = uni.getStorageSync('TOKEN');
  9. var token = _token ? 'JWT ' + _token : '';
  10. request['header'] = {
  11. 'Content-Type': 'application/x-www-form-urlencoded',
  12. 'Authorization': token
  13. }
  14. return request
  15. }
  16. // 接受数据拦截
  17. const RESPONSEINTERCPTOR = function(response) {
  18. if (response.data.code != 0) ERRINTERCPTOR(response.data.msg)
  19. return response.data;
  20. }
  21. // 报错拦截
  22. const ERRINTERCPTOR = function(err) {
  23. uni.showModal({
  24. title: "警告",
  25. content: `请求失败:${err.message || JSON.stringify(err)}`,
  26. confirmText: "关闭",
  27. showCancel: false,
  28. confirmColor: "#fbbd08"
  29. })
  30. return err
  31. }
  32. /**
  33. * request
  34. * @param {Object} options 请求参数
  35. */
  36. export default function(options) {
  37. // 开发环境 生产环境
  38. if (options.url) options.url = process.env.NODE_ENV == "development" ? REQUESTURL.development + options.url :
  39. REQUESTURL.production + options.url;
  40. return new Promise((resolve, reject) => {
  41. uni.request({
  42. ...REQUESTINTERCPTOR(options),
  43. success: res => resolve(RESPONSEINTERCPTOR(res)),
  44. fail: err => reject(ERRINTERCPTOR("请检查网络!"))
  45. })
  46. })
  47. }