Axios学习

Axios

一、API的分类

调用API的风格:restful风格与restless风格

1.1、REST(restful) API

  1. 发送请求进行CRUD哪个操作由请求方式来决定
  2. 同一个请求路径可以进行多个操作
  3. 请求方式会用到GET/POST/PUT/DELETE

1.2、非REST(restless) API

  1. 请求方式不决定请求的CRUD操作
  2. 一个请求路径只对应一个操作
  3. 一般只有GET/POST

二、使用json-server搭建REST API

1.1、json-server是什么?

用来快速搭建模拟的REST API的工具包

  • 1-搭建站点服务。
  • 2-提供数据的操作。
  1. 在线文档: https://github.com/typicode/json-server
  2. https://blog.csdn.net/u012149969/article/details/108394159

设置hosts:

  1. 打开C:\Windows\System32\drivers\etc\hosts

    127.0.0.1  zhangsan.com
    #127.0.0.1  weixin.zhangpeiyue.com
    #127.0.0.1  api.shangguigu.com
    #127.0.0.1  nihao.com
    #127.0.0.1  amitoufu.com
    

1.2、使用json-server:提供模拟数据。

  1. 安装Node
    由于json-server需要通过Node对其进行启动,所以首先要安装Node。

  2. 全局安装json-server

cnpm install json-server -g
  1. 查看版本
json-server -v
  1. 准备一份JSON文件
{
  "scoreList":[
    {
        "id":1,
        "userName":"张三",
        "age":12,"sex":"男",
        "score":{"yuWen":10,"shuXue":20,"yingYu":30}
    },
    {
        "id":2,
        "userName":"李四",
        "age":21,
        "sex":"女",
        "score":{"yuWen":12,"shuXue":45,"yingYu":37}
    },
    {
        "id":3,
        "userName":"王五",
        "age":56,
        "sex":"男",
        "score":{"yuWen":12,"shuXue":20,"yingYu":30}
    },
    {
        "id":4,
        "userName":"赵六",
        "age":23,
        "sex":"女",
        "score":{"yuWen":19,"shuXue":21,"yingYu":65}
    },
    {
        "id":5,
        "userName":"严七",
        "age":12,
        "sex":"男",
        "score":{"yuWen":34,"shuXue":67,"yingYu":43}
    },
    {
        "id":6,
        "userName":"沈八",
        "age":43,
        "sex":"女",
        "score":{"yuWen":56,"shuXue":76,"yingYu":30}
    },
    {
        "id":7,
        "userName":"钱九",
        "age":13,
        "sex":"男",
        "score":{"yuWen":24,"shuXue":89,"yingYu":30}
    },
    {
        "id":8,
        "userName":"张十",
        "age":12,
        "sex":"女",
        "score":{"yuWen":10,"shuXue":54,"yingYu":31}
    }
  ]
}
  1. 启动

    –watch:可以省略,如果省略那么数据发生变化,站点服务不会及时响应。

    –delay:指定延长响应的时间 ,单位为毫秒。

    –port:指定端口号

    –host:主机名

json-server --watch data.json --port 80 --host 127.0.0.1 --delay 2000

1.3、使用浏览器访问测试

http://localhost:3000/scoreList
http://localhost:3000/scoreList/1

1.4、使用postman测试接口

测试GET / POST / PUT / DELETE请求

三、fetch

3.1、区别一般http请求与ajax请求

  1. ajax请求是一种特别的http请求

  2. 对服务器端来说, 没有任何区别, 区别在浏览器端

  3. 浏览器端发请求: 只有XHR或fetch发出的才是ajax请求, 其它所有的都是非ajax请求

  4. 浏览器端接收到响应

    (1) 一般请求: 浏览器一般会直接显示响应体数据, 也就是我们常说的刷新/跳转页面

    (2) ajax请求: 浏览器不会对界面进行任何更新操作, 只是调用监视的回调函数并传入响应相关数据

3.2、fetch的使用

    const btns = document.querySelectorAll("button");
    btns[0].onclick = async function () {
        // 请求方式,请求地址,发送的参数,响应的结果
        // get  http://api.zhangpeiyue.com/scoreList?sex=男
        // xhr
        // const xhr = new XMLHttpRequest();
        // // xhr.responseType = "json";
        // // xhr.responseType = "json";
        // xhr.open("get","http://api.zhangpeiyue.com/scoreList?sex=男&age=12");
        // xhr.send();
        // xhr.onload = function (){
        //     console.log(xhr.response);
        // }

        // fetch:接替xhr.
        // 1-window对象下的属性,类型是一个函数。可以完成xhr所有的工作。
        // console.log(window.fetch);

        // 2-默认发送的是get请求。第一个参数是请求地址
        // fetch("http://api.zhangpeiyue.com/scoreList?sex=男&age=12");

        // 3-fetch返回的是一个promise
        // const result = fetch("http://api.zhangpeiyue.com/scoreList?sex=男&age=12");
        // console.log(result);

        // 4-promise成功的值是一个对象(value),value原型中有json属性(方法),返回的也是一个promise
        // const result = fetch("http://api.zhangpeiyue.com/scoreList?sex=男&age=12");
        // result.then(value=>{
        //     console.log(value);
        //     const res = value.json();// 将响应体的数据转换为JSON格式,并将结果作为promise的成功值
        //     console.log(res);
        // })

        // 5-获得响应体数据JSON
        // fetch("http://api.zhangpeiyue.com/scoreList?sex=男&age=12")
        //     .then(value => {
        //         return value.json();// xhr.repsonseType="json"
        //     }).then(res => {
        //         console.log(res)
        //     })

        // 6-获得响应体数据文本text
        // fetch("http://api.zhangpeiyue.com/scoreList?sex=男&age=12")
        //     .then(value => {
        //         return value.text();// xhr.responseType="text"
        //     }).then(res => {
        //     console.log(res)
        // })

        // 7-async await
        // const response = await fetch("http://api.zhangpeiyue.com/scoreList?sex=男&age=12");
        // const result = await response.json();
        // console.log(result);

        // 8-封装
        async function myFetch(url){
            const response = await fetch(url);
            const result = await response.json();
            return result;
        }
        myFetch("http://api.zhangpeiyue.com/scoreList?sex=男&age=12").then(value=>{
            console.log(value);
        })
    }
    btns[1].onclick = function(){
        // 方式1  地址1  请求头1  请求体1   响应体1
        //1- // xhr x-www-form-urlencoded
        // const xhr = new XMLHttpRequest();
        // xhr.open("post","http://api.zhangpeiyue.com/scoreList");
        // xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        // xhr.send("userName=谢霆锋&age=40");
        // xhr.onload = function(){
        //     console.log(xhr.response);
        // }

        //2- xhr application/json
        // const xhr = new XMLHttpRequest();
        // xhr.open("post","http://api.zhangpeiyue.com/scoreList");
        // xhr.setRequestHeader("Content-Type","application/json");
        // xhr.send(JSON.stringify({
        //     userName:"古天乐",
        //     age:18
        // }));
        // xhr.onload = function(){
        //     console.log(xhr.response);
        // }

        // 3-fetch application/json
        // fetch("http://api.zhangpeiyue.com/scoreList",{
        //     method:"post",
        //     headers:{
        //         "Content-Type":"application/json"
        //     },
        //     body:JSON.stringify({
        //         userName:"古巨基",
        //         age:20
        //     })
        // }).then(value=>{
        //     return value.json()
        // }).then(value=>{
        //     console.log(value);
        // })

        // 3-fetch application/x-www-form-urlencoded
        fetch("http://api.zhangpeiyue.com/scoreList",{
            method:"post",
            headers:{
                "Content-Type":"application/x-www-form-urlencoded"
            },
            body:"a=1&b=2"
        }).then(value=>{
            return value.json()
        }).then(value=>{
            console.log(value);
        })


    }
    btns[2].onclick = async function(){
        // xhr put------>post
        // const xhr = new XMLHttpRequest();
        // xhr.open("put","http://api.zhangpeiyue.com/scoreList/3");
        // xhr.setRequestHeader("Content-Type","application/json");
        // xhr.send(JSON.stringify({
        //     userName:"王源",
        //     age:18
        // }));
        // xhr.onload = function(){
        //     console.log(xhr.repsonse);
        // }

        // fetch
        // const response = await fetch("http://api.zhangpeiyue.com/scoreList/4",{
        //     method:"put",
        //     headers:{
        //         "Content-Type":"application/json"
        //     },
        //     body:JSON.stringify({
        //         userName:"赵无极",
        //         age:12
        //     })
        // })
        // const result = await response.json();
        // console.log(result);

    }
    btns[3].onclick = async function(){
        // xhr
        // const xhr = new XMLHttpRequest();
        // xhr.open("delete","http://api.zhangpeiyue.com/scoreList/3");
        // xhr.send();
        // xhr.onload = function (){
        //     console.log(xhr.response);
        // }

        // fetch
        // const response = await fetch("http://api.zhangpeiyue.com/scoreList/4",{
        //     method:"delete"
        // })
        // const result = await response.json();
        // console.log(result);
    }

    btns[4].onclick = async function(){
        // xhr
        // const xhr = new XMLHttpRequest();
        // xhr.open("PATCH","http://api.zhangpeiyue.com/scoreList/5");
        // xhr.setRequestHeader("Content-Type","application/json");
        // xhr.send(JSON.stringify({
        //     userName:"严妻"
        // }))
        // xhr.onload = function(){
        //     console.log(xhr.response);
        // }

        // fetch
        const response = await fetch("http://api.zhangpeiyue.com/scoreList/6",{
            method:"PATCH",
            headers:{
                "Content-Type":"application/json"
            },
            body:JSON.stringify({
                userName:"段正淳"
            })
        })
        const result = await response.json();
        console.log(result);
    }

四、axios的理解和使用(重点)

4.1、axios是什么?

  1. 前端最流行的ajax请求库 ,没有之一。

  2. react/vue官方都推荐使用axios发ajax请求

  3. 文档: https://github.com/axios/axios

4.2、axios特点

  1. 基于xhr + promise的异步ajax请求库
  2. 浏览器端/node端都可以使用
  3. 支持请求/响应拦截器
  4. 支持请求取消
  5. 请求/响应数据转换
  6. 批量发送多个请求 。

4.3、axios常用语法

  • 引入axios.js一

    cnpm install axios -S
    

    在html中引入

    <script src="../node_modules/axios/dist/axios.min.js"></script>
    
  • 引入axios.js二

    https://www.bootcdn.cn/axios/ 下载

  • axios(config): 通用/最本质的发任意类型请求的方式

  • axios(url[, config]): 第一个参数是地址,第二个参数是配置项。

  • axios.request(config): 等同于axios(config)

  • axios.get(url[, config]): 发get请求

  • axios.delete(url[, config]): 发delete请求

  • axios.post(url[, data, config]): 发post请求

  • axios.put(url[, data, config]): 发put请求

  • axios.defaults.xxx: 请求的默认全局配置

  • axios.interceptors.request.use(): 添加请求拦截器

  • axios.interceptors.response.use(): 添加响应拦截器

  • axios.create([config]): 创建一个新的axios实例。

  • axios.CancelToken(): 用于创建取消请求的token对象

  • axios.isCancel(): 是否是一个取消请求的错误

  • axios.all(promises): 用于批量执行多个异步请求

  • axios.spread(): 用来指定接收所有成功数据的回调函数的方法

4.4、难点语法的理解和使用

4.4.1、axios.create(config)

  1. 根据指定配置创建一个新的axios, 也就是每个新axios都有自己的配置

  2. 新axios只是没有取消请求和批量发请求的方法, 其它所有语法都是一致的

  3. 为什么要设计这个语法?

    (1) 需求: 项目中有部分接口需要的配置与另一部分接口需要的配置不太一样, 如何处理

    (2) 解决: 创建2个新axios, 每个都有自己特有的配置, 分别应用到不同要求的接口请求中

4.4.2、拦截器函数/ajax请求/请求的回调函数的调用顺序

  1. 说明: 调用axios()并不是立即发送ajax请求, 而是需要经历一个较长的流程

  2. 流程: 请求拦截器2 => 请求拦截器1 => 发ajax请求 => 响应拦截器1 => 响应拦截器2 => 请求的回调

  3. 注意: 此流程是通过promise串连起来的, 请求拦截器传递的是config, 响应拦截器传递的是response

4.4.3、取消请求

  1. 基本流程

     配置cancelToken对象
    
     缓存用于取消请求的cancel函数
    
     在后面特定时机调用cancel函数取消请求
    
     在错误回调中判断如果error是cancel, 做相应处理
    
  2. 实现功能

     点击按钮, 取消某个正在请求中的请求
    
      在请求一个接口前, 取消前面一个未完成的请求
    
  • 设置为淘宝数据源

    // 查看
    npm config get registry
    // 设置
    npm config set registry https://registry.npm.taobao.org
    

github开发者平台(api接口)

https://docs.github.com/cn
https://docs.github.com/cn/rest
https://docs.github.com/en/rest/reference/issues#create-an-issue

练习接口地址:
    https://docs.github.com/cn/rest/reference/search#search-users
    url: https://api.github.com/search/users
    query参数:
        q : 请求关键字(最终接口会返回名字中包含q指定字符的用户)

前端如何传递数据给后台

1. url (params query hash)
    适合所有的请求
2. 请求体     
    适合 post put patch请求
3. 请求头
    适合所有的请求

安装axios

npm i  axios    

使用axios函数发送请求

import axios from "axios"
    axios(config)    
    axios(url,config)  
    axios.get(url,config)  
    axios.post(url,data,config)  

使用axios实例发送请求

一个接口服务器一个实例
import axios from "axios"
const axiosIns = axios.create(config) //提取公共的请求配置
    axiosIns(config)    
    axiosIns(url,config)  
    axiosIns.get(url,config)  
    axiosIns.post(url,data,config)  

config配置

timeout: 超时时间
baseURL: 基地址
url: 接口地址
method: 请求方式
data: 请求体
headers: 请求头
params : url中query数据

拦截器

axios函数可以拥有拦截器    
axios实例也可以拥有拦截器 
   
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
});

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    return response.data;
}, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
});    

在axios中与4个位置可以修改config

优先级顺序: 1 2 3 4
1. 配置默认值
    axios.defaults.baseURL   
2. 创建实例时
    axios.create(config)    
3. 发送请求时
    axios(config)    
4. 请求拦截器的第一个回调
    axios.interceptors.request.use(function (config) {
        return config;
    });    

发送并发请求

Promise.all([请求......])    
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

十九万里

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值