• 基于Promise + XHR 封装myAxios函数


    在JavaScript中,你可以使用`Promise`和`XMLHttpRequest`(XHR)来封装一个名为`myAxios`的函数,用于执行HTTP请求。下面是一个简单的示例,它封装了GET和POST请求的基本功能:
    function myAxios(url, method = 'GET', data = null) {
        return new Promise((resolve, reject) => {
            const xhr = new XMLHttpRequest();
            xhr.open(method, url, true);

            // 设置请求头,如果需要的话
            // xhr.setRequestHeader('Content-Type', 'application/json');

            xhr.onload = function () {
                if (this.status >= 200 && this.status < 300) {
                    resolve(this.responseText);
                } else {
                    reject(new Error(this.statusText));
                }
            };

            xhr.onerror = function () {
                reject(new Error('Network Error'));
            };

            if (method === 'POST' && data) {
                xhr.setRequestHeader('Content-Type', 'application/json');
                xhr.send(JSON.stringify(data));
            } else {
                xhr.send();
            }
        });
    }

    // 使用示例:
    myAxios('https://api.example.com/data')
        .then(response => {
            console.log(response);
        })
        .catch(error => {
            console.error('Error:', error);
        });

    myAxios('https://api.example.com/submit', 'POST', { key: 'value' })
        .then(response => {
            console.log(response);
        })
        .catch(error => {
            console.error('Error:', error);
        });
    这个`myAxios`函数接受三个参数:URL、HTTP方法和请求数据。它返回一个`Promise`,当请求成功时,这个`Promise`会被解析为响应文本;当请求失败时,它会被拒绝并抛出一个错误。

    这个简单的实现并没有处理所有可能的边缘情况和特性,例如请求超时、请求取消、请求进度、HTTP认证等。如果你需要这些功能,你可能需要使用更成熟的库,如`axios`或`fetch` API。

  • 相关阅读:
    SpringBoot SpringBoot 开发实用篇 6 监控 6.1 监控的意义
    【JAVA-QA】java注释的方式/格式/特点/作用知识点
    HCIE Routing&Switching之MPLS基础理论
    Matlab:多变量数据
    国外访问学者/博士后留学人员反诈骗指南
    Elasticsearch检索
    【MySQL】Linux 中 MySQL 环境的安装与卸载
    利用DownThemAll工具批量下载网页单一链接的数据
    【测试面试】20K测试工程师会考察哪些能力?
    vue-我可以在另一个计算属性中使用计算属性吗?
  • 原文地址:https://blog.csdn.net/m0_54007573/article/details/138170103