request.js 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. import {
  2. set
  3. } from 'lodash'
  4. import WxRequest from 'mina-request'
  5. import errorCode from './errorCode.js'
  6. const {
  7. requestPath
  8. } = require('./../url.js')
  9. var app = getApp();
  10. // 对 WxRequest 进行实例化
  11. const instance = new WxRequest({
  12. baseURL: requestPath,
  13. timeout: 300000, // 超时时间
  14. isLoading: true, // 是否显示 loading 提示框
  15. header: {
  16. Authorization: "Basic bWluaTptaW5p",
  17. TENANT_ID: "1"
  18. }
  19. });
  20. // 添加请求拦截器
  21. instance.interceptors.request = (config) => {
  22. //console.log("app", app);
  23. config = Object.assign({
  24. ...instance.config,
  25. ...config
  26. });
  27. //console.log(config)
  28. const TENANT_ID = wx.getStorageSync("tenantId");
  29. const isToken = (config.header || {}).isToken === false;
  30. const token = wx.getStorageSync("access_token");
  31. if (token && !isToken) {
  32. config.header["Authorization"] = "Bearer " + token; // token
  33. } else {
  34. config.header["Authorization"] = "Basic bWluaTptaW5p";
  35. }
  36. delete config.header['isToken'];
  37. if (TENANT_ID) {
  38. config.header["TENANT_ID"] = TENANT_ID; // 租户ID
  39. }
  40. if (config.method === "post" && config.header.serialize) {
  41. config.data = serialize(config.data);
  42. delete config.data.serialize;
  43. }
  44. try {
  45. // 需要companyId和companyName参数
  46. if (!config.noCompany) {
  47. let companyId = wx.getStorageSync('companyId'),
  48. companyName = wx.getStorageSync('companyName');
  49. // companyName = wx.getStorageSync('companyName') || '';
  50. // let company_info = wx.getStorageSync('company') || {};
  51. // companyId = company_info && company_info.companyId ? company_info.companyId || '' : '';
  52. // if (!companyName) {
  53. // companyName = company_info && company_info.ownerCodeList ? company_info.ownerCodeList[0] || '' : '';
  54. // }
  55. if (config.method === 'get') {
  56. config.params = config.params || {};
  57. config.params = {
  58. companyId: companyId,
  59. companyName: companyName,
  60. ...config.params
  61. }
  62. } else {
  63. config.data = config.data || {};
  64. config.data = {
  65. companyId: companyId,
  66. companyName: companyName,
  67. ...config.data,
  68. }
  69. }
  70. }
  71. } catch (err) {
  72. console.error('参数companyId、companyName异常', err);
  73. }
  74. // 在发送请求之前做些什么
  75. return config
  76. }
  77. // 添加响应拦截器
  78. instance.interceptors.response = async (res, options) => {
  79. // response.isSuccess = true,代码执行了 wx.request 的 success 回调函数
  80. // response.isSuccess = false,代码执行了 wx.request 的 fail 回调函数
  81. // response.statusCode // http 响应状态码
  82. // response.config // 网络请求请求参数
  83. // response.data 服务器响应的真正数据
  84. //console.log(res)
  85. const status = Number(res.statusCode) || 200;
  86. let message = "";
  87. if (res.errMsg && res.errMsg == "request:fail ") {
  88. setTimeout(() => {
  89. wx.showToast({
  90. title: '网络超时,请检查网络',
  91. icon: 'none'
  92. })
  93. }, 200);
  94. return;
  95. }
  96. if (options["reSend"]) {
  97. if (options["reSend"] >= 5) {
  98. return "";
  99. }
  100. message = res.data.msg || errorCode[status] || errorCode["default"];
  101. } else {
  102. message = res.data.msg || errorCode[status] || errorCode["default"];
  103. }
  104. if (res.data.code == 1 && res.data.data == '用户不存在' && res.data.msg == '用户不存在') {
  105. wx.clearStorageSync();
  106. return Promise.reject(res);
  107. } else if (status === 401) {
  108. if (res.data.data === wx.getStorageSync('access_token') && res.data.msg === wx.getStorageSync('access_token') && res.data.code === 1) {
  109. //console.log(res);
  110. let userData = await instance.request(Object.assign({
  111. url: `/auth/oauth/token?grant_type=refresh_token&refresh_token=${wx.getStorageSync('refresh_token')}`,
  112. method: "post",
  113. header: {
  114. isToken: false,
  115. TENANT_ID: "1",
  116. Authorization: "Basic bWluaTptaW5p"
  117. },
  118. }))
  119. wx.setStorageSync('access_token', userData.data.access_token);
  120. wx.setStorageSync('refresh_token', userData.data.refresh_token);
  121. wx.setStorageSync('expires_in', userData.data.expires_in);
  122. wx.setStorageSync('isLock', false);
  123. wx.setStorageSync('lockPasswd', '');
  124. options.header.Authorization = `Basic ${userData.data.access_token}`;
  125. options["reSend"] = (options["reSend"] || 0) + 1;
  126. options.url = options.url.replace(options.baseURL, "");
  127. let reData = await instance.request(Object.assign({
  128. ...options
  129. }));
  130. return reData;
  131. }
  132. wx.clearStorageSync();
  133. setTimeout(() => {
  134. wx.showToast({
  135. title: '您的登录已过期,请重新登录或重新进入小程序',
  136. icon: "none",
  137. });
  138. }, 200);
  139. app.globalData.innerShow = null;
  140. app.globalData.changeCompanyName = null;
  141. app.globalData.token = null;
  142. app.globalData.company = null;
  143. app.globalData.userInfo = null;
  144. setTimeout(() => {
  145. wx.redirectTo({
  146. url: '/pages/login/login',
  147. });
  148. }, 2000);
  149. // store.dispatch("FedLogOut").then(() => {
  150. // router.push({
  151. // path: "/login"
  152. // });
  153. // });
  154. return;
  155. }
  156. if (res.data.access_token) {
  157. return Promise.resolve(res);
  158. }
  159. if (status !== 200 || res.data.code === 1) {
  160. if (res.data.data == 'invalid_exception') {
  161. wx.clearStorageSync();
  162. setTimeout(() => {
  163. wx.showToast({
  164. title: message,
  165. icon: "none",
  166. })
  167. }, 200);
  168. return;
  169. } else if (res.data.data == 'Full authentication is required to access this resource' || message.indexOf('Invalid refresh token:') != -1) {
  170. wx.clearStorageSync();
  171. setTimeout(() => {
  172. wx.showToast({
  173. title: '您的登录已过期,请重新登录或重新进入小程序',
  174. icon: "none",
  175. })
  176. }, 200);
  177. app.globalData.innerShow = null;
  178. app.globalData.changeCompanyName = null;
  179. app.globalData.token = null;
  180. app.globalData.company = null;
  181. app.globalData.userInfo = null;
  182. setTimeout(() => {
  183. wx.redirectTo({
  184. url: '/pages/login/login'
  185. })
  186. }, 1000);
  187. return Promise.reject(res);
  188. }
  189. if (res.config.skipError) {
  190. return Promise.reject(res);
  191. }
  192. setTimeout(() => {
  193. wx.showToast({
  194. title: message,
  195. icon: "none"
  196. })
  197. }, 200);
  198. return Promise.reject(new Error({
  199. message: message,
  200. response: res
  201. }));
  202. }
  203. // 对响应数据做点什么
  204. return res
  205. }
  206. instance.gets = (url) => {
  207. return instance.request(Object.assign({
  208. method: 'GET'
  209. }, {
  210. url
  211. }))
  212. }
  213. instance.get = (data) => {
  214. return instance.request(Object.assign({
  215. method: 'GET'
  216. }, data))
  217. }
  218. instance.post = (data) => {
  219. return instance.request(Object.assign({
  220. method: 'POST'
  221. }, data))
  222. }
  223. instance.upload = (data = {
  224. url,
  225. filePath,
  226. name: 'file'
  227. }) => {
  228. return instance.request(Object.assign({
  229. method: 'POST'
  230. }, data))
  231. }
  232. export default instance