request.js 1.3KB

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