request.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import util from './util.js';
  2. import authLogin from './autoLogin.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 authLogin().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 authLogin().then(res => {
  46. return request(api, method, data, {
  47. noAuth,
  48. noVerify
  49. });
  50. });
  51. } else {
  52. reject(res.data.msg || '系统错误');
  53. }
  54. },
  55. fail: (msg) => {
  56. reject('请求失败');
  57. }
  58. })
  59. });
  60. }
  61. ['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
  62. request[method] = (api, data, opt) => request(api, method, data, opt || {})
  63. });