当前位置:   article > 正文

vue中fetch封装_fetch vue封装

fetch vue封装
  1. export default async(url = '', data = {}, type = 'GET', method = 'fetch') => {
  2. type = type.toUpperCase();
  3. if (type == 'GET') {
  4. let dataStr = ''; //数据拼接字符串
  5. Object.keys(data).forEach(key => {
  6. dataStr += key + '=' + data[key] + '&';
  7. })
  8. if (dataStr !== '') {
  9. dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
  10. url = url + '?' + dataStr;
  11. }
  12. }
  13. if (window.fetch && method == 'fetch') {
  14. let requestConfig = {
  15. credentials: 'include',//为了在当前域名内自动发送 cookie , 必须提供这个选项
  16. method: type,
  17. headers: {
  18. 'Accept': 'application/json',
  19. 'Content-Type': 'application/json'
  20. },
  21. mode: "cors",//请求的模式
  22. cache: "force-cache"
  23. }
  24. if (type == 'POST') {
  25. Object.defineProperty(requestConfig, 'body', {
  26. value: JSON.stringify(data)
  27. })
  28. }
  29. try {
  30. const response = await fetch(url, requestConfig);
  31. const responseJson = await response.json();
  32. return responseJson
  33. } catch (error) {
  34. throw new Error(error)
  35. }
  36. } else {
  37. return new Promise((resolve, reject) => {
  38. let requestObj;
  39. if (window.XMLHttpRequest) {
  40. requestObj = new XMLHttpRequest();
  41. } else {
  42. requestObj = new ActiveXObject;
  43. }
  44. let sendData = '';
  45. if (type == 'POST') {
  46. sendData = JSON.stringify(data);
  47. }
  48. requestObj.open(type, url, true);
  49. requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  50. requestObj.send(sendData);
  51. requestObj.onreadystatechange = () => {
  52. if (requestObj.readyState == 4) {
  53. if (requestObj.status == 200) {
  54. let obj = requestObj.response
  55. if (typeof obj !== 'object') {
  56. obj = JSON.parse(obj);
  57. }
  58. resolve(obj)
  59. } else {
  60. reject(requestObj)
  61. }
  62. }
  63. }
  64. })
  65. }
  66. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/257294
推荐阅读
相关标签
  

闽ICP备14008679号