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