index.js 1.2 KB

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