axios 是什么?

  1. 前端最流行的 ajax 请求库
  2. react/vue 官方都推荐使用 axios 发 ajax 请求
  3. 文档: https://github.com/axios/axios

axios 特点

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

json-server

JSON-Server 是一个 Node 模块,运行 Express 服务器,你可以指定一个 json 文件作为 api 的数据源。如果没有写后台返回数据可以用这个来模拟后台返回的数据

安装

npm install -g json-server

在当前文件下建立db.json

{
  "persons":[
    {"id":1,"name":"zhangsan","age":18},
    {"id":2,"name":"lisi","age":19}
  ],
  "dogs":[
    {"id":1,"name":"xiaohei","age":4},
    {"id":2,"name":"xiaohuang","age":2}
  ],
  "school":{"name":"wsyu"}
}

启动 json-server

json-server可以直接把一个json文件托管成一个具备全RESTful风格的API,并支持跨域、jsonp、路由订制、数据快照保存等功能的 web 服务器

json-server --watch db.json

结果

输出一下内容即成功

\{^_^}/ hi!

  Loading db.json
  Done

  Resources
  http://localhost:3000/persons
  http://localhost:3000/dogs
  http://localhost:3000/school

  Home
  http://localhost:3000

  Type s + enter at any time to create a snapshot of the database
  Watching...

在这里插入图片描述

get请求

注意axios发送get请求要带参数时,携带的应该是params而不是data

<body>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

    <div class="container">
        <button>发送GET请求</button>
        <button>发送POST请求</button>
        <button>发送PUT请求</button>
        <button>发送DELETE请求</button>
    </div>

    <script>
        //获取按钮
       const btns= document.querySelectorAll("button");
    console.log(btns)
       //get
       btns[0].onclick=function(){
           //发送AJAX请求

            axios(
              {
                  //请求方式
              method: 'GET',
              url: "http://localhost:3000/persons",
              params: {
                  id:1
              }
             }

           ).then((response) => {
                console.log(response)
               
            });
        }
    </script>
</body>

简单写法

 btns[0].onclick=function(){
           //发送AJAX请求

        axios.get("http://localhost:3000/persons",{params:{id:1}}).then((response) => {
            console.log(response.data)
        });
        }

在这里插入图片描述

post请求

注意post请求参数是data时默认发送的数据格式是json格式参数

btns[1].onclick=function(){
          axios({
              method: 'POST',
              url: "http://localhost:3000/persons",
              data:{
                  name:"dyk",
                  age:18
              }
          }).then((response) => {
            console.log(response.data)
          });
        }

简写

axios.post("http://localhost:3000/persons",{name:'dyk123',age:21}).then(response =>{
            console.log(response.data)
        })

如果想发urlencoded形式

btns[1].onclick=function(){
          axios({
              method: 'POST',
              url: "http://localhost:3000/persons",
           
            headers:{'Content-Type':'application/x-www-form-urlencoded'},
            data:'name=cb&age=20'
          }).then((response) => {
            console.log(response.data)
          });
        }

put请求

axios({
              method: 'PUT',
              url: " http://localhost:3000/persons/1",
              data: {
                
                  name:'dyk12',
                  age:8
              }
            }).then((response) => {
            console.log(response.data)
          });

简写

 axios.put("http://localhost:3000/persons/1",{name:'rng',age:12}).then((response) => {
            console.log(response.data)
          });

delete请求

		axios({
              method: 'DELETE',
              url: "http://localhost:3000/persons/1",
              
            }).then((response) => {
            console.log(response.data)
          });

执行多个并发请求

function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // 两个请求现在都执行完成
  }));

全局的 axios 默认值

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

简写路径

可以看见上面每个请求都写了http://localhost:3000/很长一串路径,可以简写

axios.defaults.baseURL="http://localhost:3000";

后面所有的url都可以省略路径,但不能省略/

<!DOCTYPE html>
<html lang="en">
<head>
    <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>axios</title>
   
</head>
<body>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

    <div class="container">
        <button>发送GET请求</button>
        <button>发送POST请求</button>
        <button>发送PUT请求</button>
        <button>发送DELETE请求</button>
    </div>

    <script>
        //获取按钮
       const btns= document.querySelectorAll("button");

       axios.defaults.baseURL="http://localhost:3000";
  
       //get
       btns[0].onclick=function(){
           //发送AJAX请求
        axios.get("/persons",{params:{id:1}}).then((response) => {
            console.log(response.data)
        });
        }

        //post
        //添加数据
        btns[1].onclick=function(){
  
        axios.post("/persons",{name:'dyk123',age:21}).then(response =>{
            console.log(response.data)
        })
        }

        btns[2].onclick=function(){
    

        axios.put("/persons/1",{name:'rng',age:12}).then((response) => {
            console.log(response.data)
          });
        }

        btns[3].onclick=function(){
            axios({
              method: 'DELETE',
              url: "/persons/2",
              
            }).then((response) => {
            console.log(response.data)
          });
        }
    </script>
</body>
</html>

创建实例并添加配置

可以使用自定义配置新建一个 axios 实例

var instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});

用instance代替原来的axios

拦截器

在请求或响应被 then 或 catch 处理前拦截它们。

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });

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

如果你想在稍后移除拦截器,可以这样:

var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);

axios的get请求禁止缓存

用axios拦截器拦截请求,为get请求添加时间戳

//axios请求拦截器
axios.interceptors.request.use(config => {
	if (/get/i.test(config.method)) { //判断get请求
		config.params  =  config.params || {};
		config.params.t = Date.parse(new Date())/1000; //添加时间戳
	}
    return config;
}, error => {
    return Promise.reject(error);
})


Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐