封装xhr

在使用axios库时不知道什么原因一直到下面的错误
Current environment does not provide a require() for requiring ‘util’.

所以打算自己使用xhr封装一下

封装的代码如下

const ajax = ({

method = ‘get’,

url = ‘’,

params = undefined,

data = undefined,

responseType = ‘json’,

headers = {

'Content-Type': 'application/json'

},

timeout = 5000

}: config) => {

return new Promise((resolve, reject) => {

const xhr = new XMLHttpRequest();

if (params) {

  url = url + '?' + new URLSearchParams(params).toString()

}

xhr.open(method, url);

xhr.responseType = responseType;

const headKeyArr = Object.keys(headers)

// 设置请求头

for (let key of headKeyArr) {

  xhr.setRequestHeader(key, headers[key])

}

// 处理请求体

let requestData = null;

if (data) {

  if (data instanceof FormData) {

    // data是FormData类型

    requestData = data;

  } else if (data instanceof URLSearchParams) {

    // data是URLSearchParams类型

    requestData = data.toString();

    // 如用户设置了content-type请求头,则不作修改

    if (!headers["content-type"]) {

      xhr.setRequestHeader(

        "content-type",

        "application/x-www-form-urlencoded"

      );

    }

  } else if (typeof data === "object") {

    // data为普通对象

    // 只转化为JSON或url编码字符串

    if (

      headers["content-type"] === "application/x-www-form-urlencoded" ||

      headers["content-type"] === "application/json"

    ) {

      if (headers["content-type"] === "application/x-www-form-urlencoded") {

        const params = new URLSearchParams(data);

        requestData = params.toString();

      } else {

        requestData = JSON.stringify(data);

      }

    } else {

      // 默认情况下转为JSON格式

      requestData = JSON.stringify(data);

      if (!headers["content-type"]) {

        xhr.setRequestHeader("content-type", "application/json");

      }

    }

  }

}

let timer = null;

xhr.addEventListener('loadend', () => {

  clearTimeout(timer);

  timer = null;

  const status = xhr.status;

  const msg = xhr.response.data?.msg

  // 调用成功/失败的处理程序

  if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {

    resolve(JSON.parse(xhr.response))

  } else {

    if (msg) {

      console.error(msg)

    } else {

      if (status === 400) {

        console.error('请求错误')

      }

      if (status === 404) {

        console.error('接口地址不存在')

      }

      if (status === 403) {

        console.error('拒绝访问')

      }

      if (status === 500) {

        console.error('服务器错误')

      }

    }

    reject(new Error(xhr.response))

  }

})

// xhr.ontimeout = function (e) {

//   reject(new Error('请求超时'))

// };

if (timeout > 0) {

  xhr.timeout = timeout;

  // xhr.timeout超时事件

  xhr.ontimeout = function () {

    clearTimeout(timer);

    timer = null;

    reject("请求超时");

  };

  // 监听xhr对象下面的onload事件

  // 当xhr对象接收完响应数据后触发

  // xhr.onload = function () {

  //   // 清除延时器

  //   clearTimeout(timer);

  //   timer = null;

  // };

  // 网络中断或无效url

  xhr.onerror = function () {

    // 清除延时器

    clearTimeout(timer);

    timer = null;

    reject(new Error("Network Error"));

  };

  timer = setTimeout(() => {

    // 请求超时机制双重保护,调用 abort 方法终止请求

    if (timer) {

      clearTimeout(timer);

      timer = null;

      xhr.abort();

      reject("timeout");

    }

  }, timeout);

}

xhr.send(requestData);

});

}

cocos里使用axios非常麻烦,本质上cocos 对 npm的支持不够好,解决这个问题真不如自己封装一个简单的 :rofl:

这样吗,今天下午使用socket.io-client这个插件也一直报错,最后还是打算用原生websocket

有一种方案可以让cocos使用npm包,用parcel打包工具,把需要的包打包成单独的js文件,当成插件导进去就行!

主要是模块导入的问题,cocos creator不支持require

一些不涉及node本地模块的require也可以,你可以试试!

:rofl:我也是自己写了一个,结果只开头写了两句,AI直接给我生成好了 :rofl:

网络方面建议最好自己写,自己封装 才能应付复杂场景和更好拓展

图片 你是说COCOS 不能这么写?