Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

xhr封装axios #202

Open
TieMuZhen opened this issue May 11, 2022 · 0 comments
Open

xhr封装axios #202

TieMuZhen opened this issue May 11, 2022 · 0 comments

Comments

@TieMuZhen
Copy link
Owner

TieMuZhen commented May 11, 2022

xhr封装axios


const axios=({// ES6: 解构参数对象 & 指定形参默认值
    url,
    method='GET',
    params={}, // 对应生成query参数    
    data={} // 对应生成请求体参数
}) => {
    //一:创建一个promise对象,成功的结果为response, 异常的结果为error
    return new Promise((resolve, reject) => {
        //二:利用xhr创建一个ajax请求
        //2.1创建xhr对象
        const xhr = new XMLHttpRequest()
    
        //2.2.1因为get请求的请求体在URL中所以要把URL拼接一下

        // 将params中包含的所有数据拼接成url的query参数字符串
        // 根据params对象生成query参数字符串id=2&title=xxx
        let queryStr = ''
        /* Object.keys(object): 得到对象自身上所有属性名的数组 */
        Object.keys(params).forEach(key => {
            queryStr += `&${key}=${params[key]}`
        }) // &id=2&title=xxx

        if (queryStr!=='') {
            queryStr = queryStr.substring(1)  // id=2&title=xxx
            // 将queryStr接到url上
            url += '?' + queryStr // http://localhost:3000/posts?id=2&title=xxx
        } 

        //2.2打开连接(初始化请求)
        xhr.open(method, url)
        let body = null;
        if(method == "PUT" || method == "POST" || method == "PITCH") {
            // 指定请求头: Content-Type: application/json
            //因为send必须发送json数据格式,
            //因此需要在请求头中增加好并且把data对象利用json.stringify转化成json字符串
            xhr.setRequestHeader('Content-Type', 'application/json')
            body = JSON.stringify(data);
        }
        xhr.send(body);
        //2.3监视状态,如果请求成功调用reject(),失败resolve()
        xhr.onreadystatechange = function () {
            // readyState == 4 请求操作已经完成
            if (xhr.readyState == 4){
                //2.3.1获取状态
                const status = xhr.status // 响应状态码(数值)
                // 2.3.2如果请求成功(status在[200, 299])时执行resolve(response对象)
                if (status >= 200 && status < 300) {
                    const data = xhr.response // 是一个json文本
                    const response = { // 封装一个response对象
                        data: JSON.parse(data), // 4.响应json数据自动解析为js
                        status
                    }
                    resolve(response)
                } else { // 2.3.3如果请求失败时执行reject(error对象)
                    reject(new Error('request error, status is ' + status))
                }
            }
        }
    })
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant