封装axios

vue中使用axios发起请求

    let axios = {
***get请求***
        get: function (url) {
            return new Promise((resolve, reject) => {
                // 1.创建一个xhr对象
                let xhr = new XMLHttpRequest()
                // 2.与服务器建立链接
                 // 'GET'是请求方式 url是请求地址
                xhr.open('GET', url)
                // 3.发送请求
                xhr.send()
                // 4.监听服务器的状态 只要状态发生改变都会触发
                xhr.onreadystatechange = function () {
                    // console.log(xhr);
                    if (xhr.readyState == 4) {
                      //或是其他 根据后端返回的数据而定
                        if (xhr.status == 200) {
                            resolve(JSON.parse(xhr.response))
                            // console.log(JSON.parse(xhr.response));//字符串
                        }else{
                            reject("error")
                        }
                    }
                }
            })
        },
*** post请求***
        post: function (url) {
            return new Promise((resolve, reject) => {
                // 1.创建一个xhr对象
                let xhr = new XMLHttpRequest()
                // 2.与服务器建立链接
                 // 'POST'是请求方式 url是请求地址
                xhr.open('POST', url)
                // 3.发送请求
                xhr.send()
                // 4.监听服务器的状态
                xhr.onreadystatechange = function () {
                    // console.log(xhr);
                    if (xhr.readyState == 4) {
                   //或是其他 根据后端返回的数据而定
                        if (xhr.status == 200) {
                            resolve(JSON.parse(xhr.response))
                            // console.log(JSON.parse(xhr.response));//字符串
                        }else{
                            reject("error")
                        }
                    }
                }
            })
        }
    }

get 请求使用

  axios.get('你要请求的地址').then(res => {
        console.log(res);
    })

post 请求使用

//
    axios.post('你要请求的地址').then(res => {
        console.log(res);
    })
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容