Axios的使用

566 阅读5分钟

Axios简介

Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。在当今的前端开发中,不论是Vue框架还是React框架,Axios都是最常用的Ajax请求技术,所以,掌握Axios的使用是当今前端开发必备的基本技能。

json-server简介

在介绍Axios使用方法之前,先介绍一个好用的模拟请求的库——json-server。我们在工作中实际开发项目时,正常的开发流程都是前后端端先定义好相关接口,定义完成后,前后端分别开始开发工作。那么问题来了,前端在开发的过程中,可能需要请求接口数据,这个时候,后端的开发还没有完成,提供不了接口,这个时候,前端该怎么做呢?当然方法有很多。比如前端写json文件,用mock数据,这里我要介绍的就是一种模拟后端接口返回的方法:json—server。

json-server使用方法

安装

首先我们打开我们的终端(win+r)全局安装json-server,全局安装命令如下:npm install -g json-server

模拟json文件

在你想要放置json服务的文件夹下新建一个json文件,如db.json,在该文件加中写如你想要的json数据,例如:

{
  "posts": [
    {
      "id": 1,
      "title": "json-server",
      "auther": "zhangsan"
    },
    {
      "id": 2,
      "title": "json-server",
      "auther": "zhangsan"
    }
  ],
  "comment": [
    {
      "id": 1,
      "body": "some comment",
      "postId": 1
    },
    {
      "id": 2,
      "body": "some comment2",
      "postId": 2
    }
  ],
  "profile": {
    "name": "typecode"
  }
}

用vscode打开当前的文件,打开vscode终端,进入到当前json文件(db.json文件的目录下),执行json-server db.json(这里的db.json就是你自己新建的json文件)这时我们就会看到如下结果,我们看到这个笑脸hi!就代表服务已经起成功了(就这么简单,妈妈再也不用担心后端不给我起服务了)

json-server1.PNG 接着我们就可以通过下面的resources中的链接打预览下我们的服务返回的数据了。页面打开像下面这个样子:

json-server2.PNG 哈哈哈,到这里我们的服务就起好了,开心。

Axios使用

Axios安装

  1. 使用 npm:
  $ npm install axios
  1. 使用cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

小贴士:这里的cdn如果小伙伴们感觉有点慢,可以试一下过国内的资源:打开bootcdn网页,在网页中搜索Axios。

Axios的基本使用

这里我们以html页面引入CDN的形式来介绍: 代码如下:

<head>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div>
        <button style="background:#fff">发送get</button>
        <button style="background:#f00">发送post</button>
        <button style="background:#0f0">发送put</button>
        <button style="background:#00f">发送delete</button>
    </div>
</body>
    // part1
    let btns = document.querySelectorAll('button');
    // 设置默认请求地址开头
    axios.defaults.baseURL = 'http://localhost:3000';
    // 设置默认请求方式
    axios.defaults.method = 'GET';
    // 设置迷人请求参数
    axios.defaults.params = {sourceId:1000}
    // 设置默认请求超时时间,再次发送请求时间
    axios.defaults.timeout = 3000
    // GET请求
    btns[0].onclick = function(){
        axios({
            // 请求类型
            method:'GET',
            // URL
            url:'/comment'
        }).then((response) => {
            console.log(response)
        })
    }
    // post请求添加数据,数据可以通过data添加。可以看下执行结束后,请求的那个json文件中多了我们添加的数据
    btns[1].onclick = function(){
        axios({
            // 请求类型
            method:'POST',
            // URL
            url: 'http://localhost:3000/posts',
            data: {
                title:'新文化',
                author:'胡适'
            }
        }).then((response) => {
            console.log(response)
        })
    }
    // PUT请求修改某条数据
    btns[2].onclick = function(){
        axios({
            // 请求类型
            method:'PUT',
            // URL
            url: 'http://localhost:3000/posts/3',
            data: {
                title:'新文化',
                author:'王五'
            }
        }).then((response) => {
            console.log(response)
        })
    }
    // DELETE删除某条数据
    btns[3].onclick = function(){
        axios({
            // 请求类型
            method:'DELETE',
            // URL
            url: 'http://localhost:3000/posts/3',
        }).then((response) => {
            console.log(response)
        })
    }

Axios 创建实例使用

创建实例使用可以方便我们对不同的Axios进行不一样的操作:例如我们有两类请求,请求url开头不一样,我们用axios.defaults.baseURL就做不到,就可以通过Axios 创建实例的方式来实现,代码示例如下:

    // part2
    // 创建实例
    const duanzi = axios.create({
        baseURL: 'http://localhost:3000',
        timeout:2000
    })
    duanzi({
        url:'/posts'
    }).then(response=>{
        console.log(response)
    })

Axios 拦截器

有时候,我们需要在Axios请求发送前做一些处理,或者对Axios请求返回的结果做一些处理,这个时候我们的拦截器就该出场了(bgm:一剪梅)示例如下:通过axios.interceptors.request.use进行请求拦截:在这里,我们可以通过config添加一些请求的公共参数等操作,这里我们看到有两个函数参数,是不是很眼熟,跟Promise的resolve和reject函数很像,没错,因为Axios就是通过Promise来实现的,这里面的函数使用方式也和Promise一样。 通过axios.interceptors.response.use来设置响应拦截器,比如我们只要返回结果response中的data,那可以通过 return response.data的方式实现。

    // part3
    //请求拦截器
    axios.interceptors.request.use(function(config){
        console.log('请求拦截器成功');
        config.params = {sysNum: 123}
        return config
        // throw '参数出了问题'
    }, function(error){
        console.log('请求拦截器失败')
        return Promise.reject(error)
    })
    // 响应拦截器
    axios.interceptors.response.use(function(response){
        console.log('响应拦截器成功')
        return response
        // 这里可以response.data响应返回data
    },function(error){
        console.log('响应拦截器失败')
        return Promise.reject(error)
    })
    axios({
        url:'http://localhost:3000/posts'
    }).then(response=>{
        console.log(response)
    }).catch(error=>{
        console.log(error)
    })

Axios的取消请求

axios中的cancelToken属性可以用于取消axios请求。先介绍一个使用场景,比如我们点击一个按钮触发发送asios请求,在请求成功响应之前,我们又点击了一次该按钮,那么会再次出发axios请求,这个时候,我们就可以cancel掉上次的请求,示例如下:注意cancelToken中参数c是一个方法,调用该方法就可以结束我们当前这次axios请求。注册一个全局变量cancel首先置为null,在发送axios请求后,将axios.cancelToken实例中的参数(即终止本次axios请求的方法)赋值给全局变量cancel。当上一次请求还没有走到response,再次出发axios请求时,判断cancel是否为null,如果不是null则表示上次请求正在进行中,还没有走response,这时我们结束上次请求,发送当前这次请求。在上次请求成功之后,将用于存放上一次axios请求终止函数的变量置为null,这样我们就可以再进行下次请求。

    <div>
        <button>发送请求</button>
    </div>
    const btn = document.querySelectorAll('button')
    let cancel = null
    btn[0].onclick = function() {
        if(cancel !==null) {
            cancel()
        }
        axios({
            method:'GET',
            url:'http://localhost:3000/comments',
            cancelToken: new axios.CancelToken(function(c){
                cancel = c
            })
        }).then(response=>{
            cancel = null
        })
    }
    }