123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124 |
- 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 字符串发送
- });
- }
- }
|