axios初印象

前言:

首先,要明白axios是什么:axios是基于promise用于游览器和node.js的http客户端。(promise的本质是什么:分离异步数据获取和业务。)

axios的作用是什么呢:axios主要是用于向后台发起请求的,还有在请求中做更多的可控功能。

功能特性:

  • 在游览器中发送XMLHttpRequests请求

  • 在node.js中发送http请求

  • 支持Promise API

  • 拦截请求和响应

  • 转换请求和响应数据

  • 自动转换JSON数据

  • 客户端支持保护安全免受XSRF攻击

游览器支持:

基本使用方法:

axios执行GET请求

//为给定ID的user创建请求
axios.get('/user?ID=12345')
    .then(function (response) {
       console.log(response);
    })
    .catch(function(error) {
       console.log(error);
    });
    //可选地,上面的请求可以这样做
    axios.get('/user', {
       params: {
          ID: 12345
       }
    })
    .then(function (response) {
       console.log(response); 
    })
    .catch(function (error) {
       console.log(error);
    });

 axios执行POST请求

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
})
.then(function (response) {
   console.log(response);
})
.catch(function (error) {
  console.log(error);
});

 执行多个并发请求

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

get和post都是基于promise的,所以写法上很相似,是用then和catch,使用这种方法来进行发送请求。

还有一个axios重要的知识点就是拦截器。

拦截器:

在请求或相应被then或catch处理前拦截它们(拦截器可以做什么:在请求或者响应时拦截下来进行处理)

拦截器分为请求拦截器和响应拦截器

请求拦截器(interceptors.requst)是指可以拦截每次指定HTTP请求,并可修改配置项。

响应拦截器(interceptors.response)可以在每次HTTP请求后拦截每次或指定HTTP请求,并可修改返回结果项。

//添加请求拦截器
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实例添加拦截器:

var instance = axios.create();
instance.interceptors.request.use(function () {/*...*/})

 取消:

使用cancel token取消请求

可以使用CancekToken.source工厂方法创建cancel token。

参考博客:①一个axios的简单教程:https://www.jianshu.com/p/13cf01cdb81f

                  ②Vue2.0学习----axios用法详解: https://blog.csdn.net/qq_36575992/article/details/80338538

                  ③axios: https://blog.csdn.net/catiecarter/article/details/76639652

                  ④vue中使用axios的详细教程: http://www.cnblogs.com/nogodie/p/9853660.html

                  ⑤vue axios全攻略: https://www.cnblogs.com/libin-1/p/6607945.html

猜你喜欢

转载自blog.csdn.net/qq_26780317/article/details/88247587