fetch和ajax的功能相似,都是实现请求,但是多少有些兼容性问题。

    fetch优点:
    1.语法简洁,更加语义化
    2、基于标准 Promise 实现,支持 async/await

    下面是封装好的fetch(有处理兼容性):

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

    详情请看这里:这里,还有这里