fetch.js 2.3 KB

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