fetch.js 2.9 KB

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