一、启动json-server服务

详细教程:https://www.cnblogs.com/wml-it/p/16773220.html

二、搭建页面

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>axios的CRUD基本使用</title>
    <!-- 1.引入Bootstrap -->
    <link crossorigin="anonymous" href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <!-- 2.引入Axios -->
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
</head>
<body>
    <!-- 3.简单的页面布局 -->
    <div class="container">
        <h2 class="page-header">axios的CRUD基本使用</h2>
        <button class="btn btn-primary"> 发送GET请求 </button>
        <button class="btn btn-warning" > 发送POST请求 </button>
        <button class="btn btn-success"> 发送 PUT 请求 </button>
        <button class="btn btn-danger"> 发送 DELETE 请求 </button>
    </div>
    
</body>

</html>

效果:

image-20221009223411407

三、按钮绑定CRUD事件

<!-- 通过JS绑定Axios的CRUD操作 -->
    <script>
        //获取按钮
        const btns = document.querySelectorAll('button');

        //第一个:发送GET请求,查询id为2的文章
        btns[0].onclick = function(){
            //发送 AJAX 请求
            axios({
                //请求类型
                method: 'GET',
                //URL
                url: 'http://localhost:3000/posts/2',
            }).then(response => {
                console.log(response);
            });
        }

        //第二个:发送POST请求,添加一篇新的文章
        btns[1].onclick = function(){
            //发送 AJAX 请求
            axios({
                //请求类型
                method: 'POST',
                //URL
                url: 'http://localhost:3000/posts',
                //设置请求体
                data: {
                    title: "今天天气不错, 还挺风和日丽的",
                    author: "张三"
                }
            }).then(response => {
                console.log(response);
            });
        }

        //第三个:发送PUT请求,更新数据,更新文章id编号内容
        btns[2].onclick = function(){
            //发送 AJAX 请求
            axios({
                //请求类型
                method: 'PUT',
                //URL
                url: 'http://localhost:3000/posts/3',
                //设置请求体
                data: {
                    title: "今天天气不错, 还挺风和日丽的",
                    author: "李四"
                }
            }).then(response => {
                console.log(response);
            });
        }

        //第四个:删除数据,删除标题id编号为3的文章
        btns[3].onclick = function(){
            //发送 AJAX 请求
            axios({
                //请求类型
                method: 'delete',
                //URL
                url: 'http://localhost:3000/posts/3',
            }).then(response => {
                console.log(response);
            });
        }

    </script>