request.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // import {checkWxLogin} from './login.js';
  2. import util from './util.js';
  3. import {
  4. HEADER,
  5. TOKENNAME
  6. } from './../config.js';
  7. /**
  8. * 发送请求
  9. */
  10. export default function request(api, method, data, {
  11. noAuth = false, // 是否不需要认证
  12. noVerify = false // 是否不需要验证返回状态码
  13. }) {
  14. let Url = getApp().globalData.url,
  15. header = HEADER;
  16. if (!noAuth) {
  17. //登录过期自动登录
  18. // if (!Util.isLoginValid()) {
  19. // return checkWxLogin().then(res => {
  20. // return request(api, method, data, {
  21. // noAuth,
  22. // noVerify
  23. // });
  24. // });
  25. // }
  26. }
  27. if (getApp().globalData.token) {
  28. header[TOKENNAME] = 'Bearer ' + getApp().globalData.token;
  29. }
  30. return new Promise((reslove, reject) => {
  31. wx.request({
  32. url: Url + '/api/' + api,
  33. method: method || 'GET',
  34. header: header,
  35. data: data || {},
  36. success: (res) => {
  37. if (noVerify) {
  38. reslove(res.data, res);
  39. } else if (res.data.status == 200) {
  40. reslove(res.data, res);
  41. } else if (res.data.status == 402) {
  42. reslove(res.data, res);
  43. } else if ([410000, 410001, 410002].indexOf(res.data.status) !== -1) {
  44. // util.logout()
  45. // return checkWxLogin().then(res => {
  46. // return request(api, method, data, {
  47. // noAuth,
  48. // noVerify
  49. // });
  50. // });
  51. reject('请登录');
  52. } else {
  53. reject(res.data.msg || '系统错误');
  54. }
  55. },
  56. fail: (msg) => {
  57. reject('请求失败');
  58. }
  59. })
  60. });
  61. }
  62. ['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
  63. request[method] = (api, data, opt) => request(api, method, data, opt || {})
  64. });