import { _decorator, Node } from "cc"; import Utils from "./Utils"; const { ccclass, property } = _decorator; export default class Http { private static _lastLog = ""; /** * 发起一个 GET 请求 * @param {string} path 请求的 URL * @param {Object} params URL 查询参数 * @param {Object} headers 请求头 * @returns {Promise} 请求的响应数据 */ static get(path, params = {}, headers = {}) { return new Promise((resolve, reject) => { // 构建 URL 查询字符串 const queryString = Object.keys(params) .map( (key) => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}` ) .join("&"); const xhr = new XMLHttpRequest(); // 设置请求类型和 URL let fullUrl = `${path}?${queryString}`; xhr.open("GET", fullUrl, true); // 设置请求头 xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); for (const key in headers) { xhr.setRequestHeader(key, headers[key]); } // 设置请求超时(30秒) xhr.timeout = 8 * 1000; // 请求成功时调用 xhr.onload = () => { if (xhr.status >= 200 && xhr.status < 300) { try { // 解析 JSON 响应 const responseData = JSON.parse(xhr.responseText); if ("1" == Utils.getQueryString("log")) { if (Http._lastLog != fullUrl) { console.log(fullUrl); console.log(responseData); Http._lastLog = fullUrl; } } resolve(responseData); } catch (error) { console.error(error); reject(-1); } } else { reject(xhr.status); } }; // 请求失败时调用 xhr.onerror = () => { reject(-1); }; // 超时处理 xhr.ontimeout = () => { reject(-1); }; // 发送请求 xhr.send(); }); } static post(url, data, headers = {}) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); // 设置请求类型和 URL xhr.open("POST", `${url}`, true); // 设置请求头 xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); for (const key in headers) { xhr.setRequestHeader(key, headers[key]); } // 设置请求超时(30秒) xhr.timeout = 8*1000; // 请求成功时调用 xhr.onload = () => { if (xhr.status >= 200 && xhr.status < 300) { try { // 解析 JSON 响应 const responseData = JSON.parse(xhr.responseText); resolve(responseData); } catch (error) { reject(-1); } } else { reject(xhr.status); } }; // 请求失败时调用 xhr.onerror = () => { reject(-1); }; // 超时处理 xhr.ontimeout = () => { reject(-1); }; // 发送请求 xhr.send(JSON.stringify(data)); // 将数据转换为 JSON 字符串发送 }); } }