request.js 1.5 KB

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