简单的axios请求(GET\POST\PUT\DELETE)


<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
 
<body>
    <div>
        <button οnclick="testGet()">GET请求</button>
        <button οnclick="testPOST()">POST请求</button>
        <button οnclick="testPUT()">PUT请求</button>
        <button οnclick="testDELETE()">DELETE请求</button>
    </div>
</body>
<script>
    // GET:从服务器端读取数据
    function testGet() {
    
    
        axios({
    
    
            url: 'http://localhost:3000/posts',
            method: 'GET',
            params: {
    
    
                id: '1',
                xyz: 'lm'
            }
        }).then(
            response => {
    
    
                console.log(response)
            },
            error => {
    
    
                console.log(error.message)
            }
        )
    }
    // POST:向服务器端添加新数据,效果在db.json文件里面查看
    function testPOST() {
    
    
        axios({
    
    
            url: 'http://localhost:3000/posts',
            method: 'POST',
            data: {
    
    
                "title": "post添加或者保存数据",
                "author": "Flintstone",
            }
        }).then(
            response => {
    
    
                console.log(response)
            },
            error => {
    
    
                console.log(error.message)
            }
        )
    }
    // PUT:更新服务器端已经存在的数据,效果在db.json文件里面查看
    function testPUT() {
    
    
        axios({
    
    
            url: 'http://localhost:3000/posts/1',
            method: 'put',
            data: {
    
    
                title: 'post测试已被put更新',
                author: 'Flintstone'
            }
        }).then(
            response => {
    
    
                console.log(response)
            },
            error => {
    
    
                console.log(error.message)
            }
        )
    }
    //DELETE:删除服务器端数据,效果在db.json文件里面查看
    function testDELETE() {
    
    
        axios({
    
    
            url: 'http://localhost:3000/posts/1',
            method: 'delete',
        }).then(
            response => {
    
    
                console.log(response)
            },
            error => {
    
    
                console.log(error.message)
            }
        )
    }
 
 
    /*
        1函数的返回值为 promise,成功的结果为 response,异常的结果为eror
        2.能处理多和类型的请求:GET/POST/PUT/ DELETE
        3,函数的参数为一个配置对象
            {
                url:'', 	//请求地址
                method:'',	//请求方式GET/POST/PUT/ DELETE
                params:{},	//GET/ DELETE请求的 query参数
                data:{},	//POST或 DELETE请求的请求体参数
            }
        4.响应json数据自动解析为js
    */
    function axios({
    
    
        url,
        method = 'GET',
        params = {
    
    },
        data = {
    
    }
    }) {
    
    
        //返回一个promise对象
        return new Promise((resolve, reject) => {
    
    
            //处理method(转大写)
            method = method.toUpperCase()
 
            //处理query参数(拼接到url上) id=1&xyz=lm
            /*
                {
                    id = 1 ,
                    xyz = 'lm'
                }
            */
            let queryString = ''
            Object.keys(params).forEach(key => {
    
    
                queryString += `${
    
    key}=${
    
    params[key]}&`
            })
            if (queryString) {
    
    //id=1&xyz=lm
                //去除最后的&
                queryString = queryString.substring(0, queryString.length - 1)
                //接到url
                url += '?' + queryString
            }
 
            //1.执行一步ajax请求
            //创建xhr对象
            const request = new XMLHttpRequest()
            //打开连接(初始化请求)
            request.open(method, url, true)
            //绑定状态改变的监听
            request.onreadystatechange = function () {
    
    
                //如果没有完成,直接结束
                if (request.readyState !== 4) {
    
    
                    return
                }
                //如果响应状态码在[200,300]之间代表成功,否则失败
                const {
    
     status, statusText } = request
                //2.1 如果请求成功了,调用resolve()
                if (status >= 200 && status <= 299) {
    
    
                    //准备结果数据对象response
                    const response = {
    
    
                        data: JSON.parse(request.response),
                        status,
                        statusText
                    }
                    resolve(response)
                } else {
    
    
                    //2.2如果请求失败了,调用reject()
                    reject(new Error('request error status is ' + status))
                }
            }
            //发送请求
            if (method === 'GET' || method === 'DELETE') {
    
    
                request.send()
            } else if (method === 'POST' || method === 'PUT') {
    
    
                request.setRequestHeader('Content-Tyep', 'application/json;charset=utf-8')//告诉服务器请求体的格式是json
                request.send(JSON.stringify(data))//发送json格式请求体参数
            }
 
            //2.1.如果请求成功了,调用resolve()
 
            //2.2.如果请求失败了,调用reject()
 
 
        })
    }
</script>

猜你喜欢

转载自blog.csdn.net/Dilemma_me/article/details/105582713