fetch.js 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import { appVersionCode, baseAPIUrl } from '@/http/configAPI.js'
  2. import { getChromeStorage } from '@/uilts/chromeExtension.js'
  3. export async function commonFetch({ url = '', method = 'POST', params = {}, baseInfo = {} }) {
  4. try {
  5. let deviceInfo = await getChromeStorage('deviceInfo') || {};
  6. let storage_mid = await getChromeStorage('mid').catch((error) => {console.log(error) }) || ''
  7. const { mid } = storage_mid || {}
  8. if (!baseInfo.token || !baseInfo.uid) {
  9. const { accessToken: token = '', uid = '' } = await getChromeStorage('userInfo').catch((error) => {console.log(error) }) || {}
  10. baseInfo.token = token
  11. baseInfo.uid = uid
  12. }
  13. baseInfo.mid = mid
  14. baseInfo.appVersionCode = appVersionCode
  15. baseInfo.machineCode = mid
  16. baseInfo.appType = 1
  17. baseInfo.loginUid = baseInfo.uid
  18. baseInfo.deviceId1 = deviceInfo.deviceId1;
  19. baseInfo.deviceId2 = deviceInfo.deviceId2;
  20. return new Promise(function (resolve, reject) {
  21. let _url = baseAPIUrl + url
  22. if (url.includes('http')) {
  23. _url = url
  24. }
  25. let bodyObj = {
  26. "baseInfo": baseInfo,
  27. "params": params
  28. };
  29. fetch(_url, {
  30. method: method, // or 'PUT'
  31. cache: 'no-cache',
  32. headers: {
  33. 'Content-Type': 'application/json',
  34. },
  35. body: JSON.stringify(bodyObj),
  36. })
  37. .then(response => response.json())
  38. .then(data => {
  39. switch (data.code.toString()) {
  40. // twitter授权失效
  41. case '1003':
  42. chrome.storage.local.remove("userInfo");
  43. chrome.runtime.sendMessage(
  44. { actionType: "POPUP_LOGIN", data: "" },
  45. (response) => {
  46. console.log("res", response);
  47. }
  48. )
  49. break;
  50. // 登陆token失效
  51. case '-107':
  52. chrome.storage.local.remove("userInfo");
  53. chrome.runtime.sendMessage(
  54. { actionType: "POPUP_LOGIN", data: "" },
  55. (response) => {
  56. console.log("res", response);
  57. }
  58. )
  59. break;
  60. }
  61. resolve(data);
  62. })
  63. .catch((error) => {
  64. if (!error) {
  65. error = {}
  66. }
  67. reject({
  68. url: _url,
  69. error: { message: error.message, stack: error.stack },
  70. requestParams: bodyObj
  71. });
  72. });
  73. })
  74. } catch (error) {
  75. console.log('error', error)
  76. }
  77. }