axios官方有关介绍及axios拦截器

初学vue的axios,总结方便自己看和学习
安装
使用 npm:
$ npm install axios
使用 bower:
$ bower install axios
使用 cdn:


首先要明白的是axios是什么:axios是基于promise(诺言)用于浏览器和node.js是http客户端。
axios的作用是什么呢:axios主要是用于向后台发起请求的,还有在请求中做更多是可控功能。

特点
支持浏览器和node.js
支持promise
能拦截请求和响应
能转换请求和响应数据
能取消请求
自动转换JSON数据
浏览器支持防止CSRF(跨站请求伪造)
这里你一定会想promise是什么,以下是promise的个人理解:
promise是什么:是一个对象用来传递异步操作的信息,它代表了某个未来才会知道结果的事件(通常是一个异步操作),并且这个事件提供统一的api,可供进一步的处理。
promise的作用:Promise的出现主要是解决地狱回调的问题,比如你需要结果需要请求很多个接口,这些接口的参数需要另外那个的接口返回的数据作为依赖,这样就需要我们一层嵌套一层,但是有了Promise 我们就无需嵌套。
promise的本质是什么:分离异步数据获取和业务
基本使用方法

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);
  });

执行 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/permissions');
}

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

get和post都是基于promise的所以写法上很相似,是用then和catch,使用这种方法来进行发送请求。
拦截器
在请求或响应被 then 或 catch 处理前拦截它们(拦截器可以做什么:在请求或者响应时拦截下来进行处理)
拦截器分为请求拦截器和响应拦截器
请求拦截器(interceptors.requst)是指可以拦截每次或指定HTTP请求,并可修改配置项。
响应拦截器(interceptors.response)可以在每次HTTP请求后拦截住每次或指定HTTP请求,并可修改返回结果项。
拦截器工作流程
axios官方有关介绍及axios拦截器_第1张图片
移除拦截器

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

自定义 axios 实例添加拦截器

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

你可能感兴趣的:(知识总结,axios,axios拦截器)