少于 1 分钟阅读

const baseUrl = "http://localhost:3000/api";
export default cc.http = function (options) {
  return new Promise((resolve, reject) => {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4 && xhr.status >= 200 && xhr.status < 300) {
        var res = JSON.parse(xhr.responseText);
        resolve(res);
      }
    };
    xhr.timeout = options.timeout || 50000; // 5 seconds for timeout
    var method = options.method || "GET";
    var url = options.url;
    options.data = options.data || {};
    if (method == "get" || method == "GET") {
      var url = baseUrl + options.url;
      xhr.open(method, url, true);
      xhr.send();
    } else {
      xhr.open(method, options.url, true);
      xhr.setRequestHeader("Content-type", "application/json;charset=utf-8");
      xhr.send(JSON.stringify(options.data));
    }
  });
};


const http = require("./utils/HttpHelper");
cc.Class({
extends: cc.Component,

properties: {
label: {
default: null,
type: cc.Label,
},
// defaults, set visually when attaching this script to the Canvas
text: ",欢迎来到cocos开发",
},
// use this for initialization
onLoad: async function () {
let options = {
url: "/app/list",
};
const res = await http(options);
console.log(res);
this.label.string = res;
},
update: function (dt) {},
});

留下评论