axios

文章目录

json

1、全局安装

npm install -g json-server

创建一个data.json文件

json-server --watch data.json,打开这个文件。不过会报错,提示port错误。json-server --watch data.json --port 3000,才能成功。(这是因为版本太低)

原因:是json-server的版本太低,卸载重新

打开http://localhost:3000/stus得到数据

2、通过索引修改数据

这个不知道啥数据库

3、axios 实战

注意点:
1、需要安装json。
2、引入axios链接的网站是bootcdn.cn。里面的链接时间久了可能会失效而报错,报错后网站上找新的链接。(那是因为到了21.30会失效)

3、属于打开json模拟数据库,json文件和html文件

这是文档http://www.axios-js.com/zh-cn/docs/#请求配置

需要引入axios地址,需要在网站是查询地址

bash 复制代码
<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.7.2/axios.min.js"></script>

这个是json,模拟数据库,上面有讲

c 复制代码
//data.json
{
  "stus": [
    {
      "id": "1001",
      "name": "小米",
      "age": 20,
      "classId": "1"
    },
    {
      "id": "1002",
      "name": "小名",
      "age": 25,
      "classId": "1"
    },
    {
      "id": "1003",
      "name": "小冻",
      "age": 28,
      "classId": "1"
    },
    {
      "id": "1004",
      "name": "小风",
      "age": 21,
      "classId": "1"
    },
    {
      "id": "1005",
      "name": "小红"
    }
  ],
  "calsses": [
    {
      "id": "1",
      "title": "web班",
      "stuIds": [
        "1001",
        "1002",
        "1003"
      ]
    },
    {
      "id": "2",
      "title": "java班",
      "stuIds": [
        "1004"
      ]
    }
  ]
}

get请求,post请求,delete请求,put请求,patch请求

c 复制代码
//html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>01发送get和post请求</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/1.7.2/axios.min.js"></script>
</head>
<body>
        <!-- 使用axios

        1.引入axios -->
    <button id="getNode">发送get请求</button>
    <button id="postNode">发送post请求</button>
    <button id="deleteNode">发送deleteNode请求</button>
    <button id="putNode">发送put请求</button>
    <button id="patchNode">发送patch请求</button>

    <script>
        // console.log(axios);
        // console.dir(axios);
        //get请求
        getNode.onclick = function(){
           const p = axios.get("http://localhost:3000/stus")
           console.log(p); 
        //不带参数的ajax请求
            axios.get("http://localhost:3000/stus").then(result => {
                console.log(result);
                // const {data} = result;//获取服务器端的响应数据
                // console.log(data)
                
            }).catch(err =>{
                console.log(err);
                
            })
            //带有参数的ajax数据
            axios.get("http://localhost:3000/stus/1001").then(result => {
                console.log(result);

            }).catch(err =>{
                console.log(err);
                
            })
            //发送带有?参数的数据
            axios.get("http://localhost:3000/stus?age=18").then(result => {
                console.log(result);  

            }).catch(err =>{
                console.log(err);
                
            })
            // url与参数相分离
            axios.get("http://localhost:3000/stus",{
                params:{
                    age:18
                }
            }).then(result => {
                console.log(result);  

            }).catch(err =>{
                console.log(err);
                
            })
          

           
        }  
        //发送post请求,这个是添加数据,添加1005
        postNode.onclick = function(){
            axios.post("http://localhost:3000/stus",{
                id:"1005",
                name:"小红"
            }).then(result => {
                console.log(result);  

            }).catch(err =>{
                console.log(err);
                
            })

        }
        //发送delete请求,这个是删除数据。删除1005
        deleteNode.onclick = function(){
            axios.delete("http://localhost:3000/stus/1005")
            .then(result => {
                console.log(result);  

            }).catch(err =>{
                console.log(err);
                
            })
        }
        // 发送put请求,这是修改数据改成小铭,id要写在地址上,这个与其他请求不同。
        putNode.onclick = function(){
            axios.put("http://localhost:3000/stus/1002",{

                name: "小铭"

            }).then(result => {
                console.log(result);  

            }).catch(err =>{
                console.log(err);
                
            })
        }
        //patch请求,修改为小红不修改其他数据?
        patchNode.onclick = function(){

            axios.patch("http://localhost:3000/stus/1002",{

                name: "小红"

            }).then(result => {
                console.log(result);  

            }).catch(err =>{
                console.log(err);
                
            })
        }
    </script>
</body>
</html>

配置文件和post添加数据

cpp 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>02配置文件发送请求</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/1.7.8/axios.min.js"></script>
</head>
<body>
    <button id="sendRequestNode">发送请求</button>
    <button id="sendRequestgetNode">发送get请求</button>
    <button id="sendRequestpostNode">发送post请求</button>
    <script>
        sendRequestpostNode.onclick = function() {
           axios({
                url:"/stus",
                method:"post",
                baseURL:"http://localhost:3000",
                //只适用于put,post,patch
                //添加
                data:{
                    id:"1005",
                    name:"小强",
                    age:19,
                    calssId:1
                }
           }) .then(resunt =>{
                console.log(resunt);
                console.log("添加成功");
                
            }).catch(err => {
                console.log(err);
                
            })
        }

        sendRequestNode.onclick = function(){
            //获取所有学生数据
            axios({
            //配置请求的url,将参数写在了url上
            // url:"/stus?age=18",
            //请求地址和参数分开
            url:"/stus",
            params:{
                age:18
            },
            //配置请求类型,默认get
            method:"get",
            //基础路径   请求路径 = 基础路径(协议,ip,端口) + 项目路径
            baseURL:"http://localhost:3000"
            }).then(resunt =>{
                console.log(resunt);
                
            }).catch(err => {
                console.log(err);
                
            })
        }
    </script>
</body>
</html>

使用 transformRequest ,过滤数据更改

允许在向服务器发送前,修改请求数据

transformRequest:修改发送到服务器的请求数据。

transformResponse:修改从服务器返回的响应数据

下面是因为json server版本太低而报错

浏览器 报错

xhr.js:195 POST http://localhost:3000/stus 500 (Internal Server Error)

服务器 报错

SyntaxError: Unexpected token i in JSON at position 0

json server 运行报错

http://undefined:3000/stus

http://undefined:3000/calsses

cpp 复制代码
 sendRequestFilterNode.onclick = function() {
           axios({
                url:"/stus",
                method:"post",
                baseURL:"http://localhost:3000",
                // data : {
                //     a:"",
                // },
                data:{
                    id:"1005",
                    name:"小强",
                    age:19,
                    calssId:1
                },
              //这个是固定写死的写法
            //     transformRequest: [function (data,headers) {
            //         console.log(data);
            //         //对data进行任意转换处理,过滤后的数据 key = value
            //         //id=1005&name=小明&age=19&classId=1
            //         return 'id=1005&name=小明&age=19&classId=1';
            //         // return data;
            //   }],
    		//这个是没有写死可以修改数据
            transformRequest: [function (data, headers) {
                data.name = "小明"
                data.age = 11
                let params = ""
                //这个是简化写法,这是最常用的,还可以使用拦截器,文档有说
                // const params = new URLSearchParams(data).toString()
                // 将请求过来的参数name的值由小强变成小明
                //循环
                for(const [key,value] of Object.entries(data)){
                //需要返回'id=1005&name=小明&age=19&classId=1',这样的字符串才能写到data.json里面,所以才这样写
                    params += `${key}=${value}&`
                    console.log(params)

                }
                if(params) {
                //长度减1,如果params不为空,就减去最后一个字符
                    params = params.substring(0,params.length - 1)
                }

                 return params;  

             }],
           }) .then(result =>{
                console.log(result);
                console.log("添加成功");
                
            }).catch(err => {
                console.log(err);
                
            })
        }

transformResponse响应数据

响应回来数据,然后更改

cpp 复制代码
sendResponseFilterNode.onclick = function () {
            axios({
                url: "/stus",
                params: {
                    age: 21
                },
                method: "get",
                baseURL: "http://localhost:3000",
                //响应数据的过滤
                transformResponse: [function (data) {
                    // data响应回来的数据是一个字符串
                    // console.log("####",data)
                    const dataObj = JSON.parse(data)
                    dataObj[0].name = '小绿'
               // 对 data 进行任意转换处理
                return dataObj;
             }],


            }).then(result => {
                console.log("xxxxx",result.data);

            }).catch(err => {
                console.log(err);

            })
        }

请求头配置

1.获取网站

2.获取请求头

cpp 复制代码
sendRequestHeaderNode.onclick = function () {
            // 获取电影数据
            axios({
                url: "/gateway",
                params: {
                    cityId: 440300,
                    pageNum: 1,
                    pageSize: 10,
                    type:1,
                    k:2663425
                },
                method: "get",
                baseURL: "https://m.maizuo.com",

            //  添加请求头
            //  headers: {'X-Requested-With': 'XMLHttpRequest'},
             headers: {
                'x-client-info':'{"a":"3000","ch":"1002","v":"5.2.1","e":"17400546045750037791375361"}',
                'x-host':'mall.film-ticket.film.list'
            },

            }).then(result => {
                console.log(result.data);

            }).catch(err => {
                console.log(err);

            })
        }

然后就能获取数据

全局配置

比如说这样就能获取http://localhost:3000/stus,axios({})里面就不要在写http://localhost:3000,这样能简化代码

cpp 复制代码
axios.defaults.baseURL = 'http://localhost:3000';
 axios({
                url: "/stus",
)}

还能全局配置请求头等等

拦截器

请求拦截器/响应拦截器适用场景
        多个请求或者多个响应 请求过滤 和 响应的过滤 都是一样的(业务逻辑相同)
        那么我们可以事情 请求/响应拦截器

        如果多个请求或者多个响应 各个相同 或者时有一个不一样
        那么必须要进行局部配置,使用
        transformRequest
        transformResponse
cpp 复制代码
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/1.7.8/axios.min.js"></script>
    <title>04.拦截器</title>
</head>

<body>

    <button id="requestNode">请求拦截器</button>
    <button id="responseNode">响应拦截器</button>

    <script>
        /*
        请求拦截器/响应拦截器适用场景
            多个请求或者多个响应 请求过滤 和 响应的过滤 都是一样的(业务逻辑相同)
            那么我们可以事情 请求/响应拦截器

            如果多个请求或者多个响应 各个相同 或者时有一个不一样
            那么必须要进行局部配置,使用
            transformRequest
            transformResponse

        */
        // // 添加请求拦截器
        // axios.interceptors.request.use(function (config) {
        //     // 请求时获取到的数据
        //     // config.data   {key:value...}
        //     // 修改了请求参数
        //     config.data.name = "小明"
        //     // 在发送请求之前做些什么
        //     return config;
        // }, function (error) {
        //     // 对请求错误做些什么
        //     return Promise.reject(error);
        // });
        // 添加响应拦截器
        axios.interceptors.response.use(function (response) {
            // 对响应数据做点什么
           
            response .data[0].name = '小绿' 
            return response;
        }, function (error) {
            // 对响应错误做点什么
            return Promise.reject(error);
        });
        requestNode.onclick = function () {
            axios({
                url: "/stus",
                method: "post",
                baseURL: "http://localhost:3000",

                data: {
                    id: "1005",
                    name: "小强",
                    age: 19,
                    calssId: 1
                },
                // transformRequest: [function (data, headers) {
                //     data.name = "小明"
                //     data.age = 11
                //     let params = ""
                //     //这个是简化,还可以使用拦截器,文档有说
                //     // const params = new URLSearchParams(data).toString()
                //     // 将请求过来的参数name的值由小强变成小明
                //     for (const [key, value] of Object.entries(data)) {
                //          //需要返回'id=1005&name=小明&age=19&classId=1',这样的字符串才能写到data.json里面,所以才这样写
                //         params += `${key}=${value}&`
                //         console.log(params)

                //     }
                //     if (params) {
                //         // 如果params不为空,就减去最后一个字符
                //         params = params.substring(0, params.length - 1)
                //     }

                //     return params;

                // }],


            }).then(result => {
                console.log(result);
                console.log("添加成功");

            }).catch(err => {
                console.log(err);

            })
        }
        responseNode.onclick = function () {
            axios({
                url: "/stus",
                params: {
                    age: 21
                },
                method: "get",
                baseURL: "http://localhost:3000",

                // transformResponse: [function (data) {

                //     const dataObj = JSON.parse(data)
                //     dataObj[0].name = '小绿'

                //     return dataObj;

                // }],


            }).then(result => {
                console.log("修改后的数据", result.data);

            }).catch(err => {
                console.log(err);

            })
        }

    </script>
</body>

</html>
相关推荐
林的快手4 小时前
CSS列表属性
前端·javascript·css·ajax·firefox·html5·safari
来一碗刘肉面9 小时前
React - ajax 配置代理
前端·react.js·ajax
csdn_aspnet11 小时前
ASP.NET MVC AJAX 文件上传
ajax·asp.net·mvc
whisperrr.19 小时前
【JavaWeb12】数据交换与异步请求:JSON与Ajax的绝妙搭配是否塑造了Web的交互革命?
前端·ajax·json
csdn_aspnet2 天前
JavaScript AJAX 库
javascript·ajax
林的快手3 天前
伪类选择器
android·前端·css·chrome·ajax·html·json
还是鼠鼠3 天前
详细介绍:封装简易的 Axios 函数获取省份列表
前端·javascript·vscode·ajax·前端框架
不会&编程6 天前
第四章 Vue 中的 ajax
前端·vue.js·ajax
Leven1995277 天前
Spark 性能优化 (三):RBO 与 CBO
ajax·性能优化·spark