axios的使用详解

简介

Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。

特点:

  • 从浏览器中创建 XMLHttpRequests
  • 从 node.js 创建 http 请求
  • 支持 Promise API
  • 拦截请求和响应(比如:在请求前添加授权和响应前做一些事情)
  • 转换请求数据和响应数据(比如:进行请求加密或者响应数据加密)
  • 取消请求
  • 自动转换 JSON 数据
  • 客户端支持防御 XSRF

axios的引入

使用 npm

npm install axios

使用 bower

bower install axios

 

使用 cdn

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

axios的使用

通过向 axios 传递相关配置对象来创建请求:axios(config) ,config是一个配置对象

// 案例:发送 POST 请求
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

只传入路径默认发起get请求:axios(url[, config])

// 发送 GET 请求(默认的方法)
axios('/user/12345');

还可以通过方法别名创建请求

axios.request(config) 
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])

axios解决并发请求

很多时候,我们可能需要同时调用多个后台接口,就会高并发的问题。axios.all()、axios.spread() 两个静态方法用于处理同时发送多个请求,可以实现在多个请求都完成后再执行一些逻辑,该方法是基于promise.all的。

axios.all(iterable):传入一个函数数组,函数中将需要并发执行的请求返回

axios.spread(callback):传入一个回调函数,再把自身在 axios.all().then() 中作为回调传入,回调函数中的参数就是多个请求的返回的结果

//在methods中定义请求方法,并return出去,不要写请求回调then()
methods:{
  getAllTask:function(){
   console.log('调用第一个接口')
   return this.$axios({
            url:'http://192.168.*.**:***/api/getTask/getAllData',
            method:'GET',
            params:{
              offset:1,
              pageSize:10
            }
          })
  },
  getAllCity:function(){
   console.log('调用第二个接口')
   return this.$axios({
              url:'http://192.168.*.**:***/city/getCities',
              method:'GET',
            })
  }
},
//在mounted周期同时发送两个请求,并在请求都结束后,输出结果
mounted:function(){
  var _this = this;  //注意!一定要重新定义一下this指向
  this.$axios.all([_this.getAllTask(),_this.getAllCity()])
  .then(_this.$axios.spread(function(res1, res2){
      console.log('所有请求完成')
      console.log('请求1结果',res1)
      console.log('请求2结果',res2)
  }))
}

总结:两个请求执行完成后,才执行 axios.spread() 中的函数,且 axios.spread() 回调函数的的返回值中的请求结果的顺序和请求的顺序一致

创建axios实例对象

使用axios.create([config]),根据指定配置创建一个新的 axios, 也就就每个新 axios 都有自己的配置,新 axios 只是没有取消请求和批量发请求的方法, 其它所有语法都是一致的。

应用场景

我们会遇到这样一个问题,后台多个接口的部分配置都是相同的,但我们仍需使用多个axios,那么我们多给请求就会面临写多个配置,每次都要重复配置 url,header,type 等等。看下面我们是怎么来解决他。

1.创建一个新的axios传入共同的配置:

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

2.发起请求,有两种方式

//方式一 : 默认get方法
//因为全局 instance 中的baseURL 已经配置 https://some-domain.com/api/',我们需要在使用的时候,写接口名字就可以了,不需要写前面域名了
instance({
url: '/posts'
})
 
//方式二 : 方法别名
instance.get('/posts')

还有时候在项目中部分接口需要的配置与另一部分接口需要的配置不太一样,这时可以创建多个新的 axios, 每个都有自己特有的配置, 分别应用到不同配置的接口请求中。比如:假如同一个项目,你要从不同的 url 地址来请求接口怎么办?

const baseURL1 = "https://127.0.0.1:3000/api";
const baseURL2 = "https://127.0.0.1:3001/api";
const baseURL3 = "https://127.0.0.1:3002/api";

//这时可以创建多个不同的axios,是不是就可以轻松解决。
let instance1 = axios.create({
  baseURL: baseURL1,
  timeout: 1000,
  headers: { "X-Custom-Header": "foobar" },
});

let instance2 = axios.create({
  baseURL: baseURL2,
  timeout: 1000,
  headers: { "X-Custom-Header": "foobar" },
});

let instance3 = axios.create({
  baseURL: baseURL3,
  timeout: 1000,
  headers: { "X-Custom-Header": "foobar" },
});

请求配置

这些是创建请求时可以用的配置选项。只有 url 是必需的。如果没有指定 method,请求将默认使用 get 方法。

{
   // 请求的服务器 URL
  url: '/user',

  // 创建请求时使用的方法
  method: 'get', // default

  // `baseURL` 将自动加在 `url` 前面
  // 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL
  baseURL: 'https://some-domain.com/api/',

  // `transformRequest` 允许在向服务器发送前,修改请求数据
  // 只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法
  // 后面数组中的函数必须返回一个字符串,或 ArrayBuffer,或 Stream
  transformRequest: [function (data, headers) {
    // 对 data 进行任意转换处理
    return data;
  }],

  // `transformResponse` 在传递给 then/catch 前,允许修改响应数据
  transformResponse: [function (data) {
    // 对 data 进行任意转换处理
    return data;
  }],

  // `headers` 是即将被发送的自定义请求头
  headers: {'X-Requested-With': 'XMLHttpRequest'},

  // `params` 是即将与请求一起发送的 URL 参数
  // 必须是一个无格式对象(plain object)或 URLSearchParams 对象
  params: {
    ID: 12345
  },

   // `paramsSerializer` 是一个负责 `params` 序列化的函数
  // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
  paramsSerializer: function(params) {
    return Qs.stringify(params, {arrayFormat: 'brackets'})
  },

  // `data` 是作为请求主体被发送的数据
  // 只适用于这些请求方法 'PUT', 'POST', 和 'PATCH'
  // 在没有设置 `transformRequest` 时,必须是以下类型之一:
  // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  // - 浏览器专属:FormData, File, Blob
  // - Node 专属: Stream
  data: {
    firstName: 'Fred'
  },

  // `timeout` 指定请求超时的毫秒数(0 表示无超时时间)
  // 如果请求话费了超过 `timeout` 的时间,请求将被中断
  timeout: 1000,

   // `withCredentials` 表示跨域请求时是否需要使用凭证
  withCredentials: false, // default

  // `adapter` 允许自定义处理请求,以使测试更轻松
  // 返回一个 promise 并应用一个有效的响应 (查阅 [response docs](#response-api)).
  adapter: function (config) {
    /* ... */
  },

 // `auth` 表示应该使用 HTTP 基础验证,并提供凭据
  // 这将设置一个 `Authorization` 头,覆写掉现有的任意使用 `headers` 设置的自定义 `Authorization`头
  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },

   // `responseType` 表示服务器响应的数据类型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
  responseType: 'json', // default

  // `responseEncoding` indicates encoding to use for decoding responses
  // Note: Ignored for `responseType` of 'stream' or client-side requests
  responseEncoding: 'utf8', // default

   // `xsrfCookieName` 是用作 xsrf token 的值的cookie的名称
  xsrfCookieName: 'XSRF-TOKEN', // default

  // `xsrfHeaderName` is the name of the http header that carries the xsrf token value
  xsrfHeaderName: 'X-XSRF-TOKEN', // default

   // `onUploadProgress` 允许为上传处理进度事件
  onUploadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
  },

  // `onDownloadProgress` 允许为下载处理进度事件
  onDownloadProgress: function (progressEvent) {
    // 对原生进度事件的处理
  },

   // `maxContentLength` 定义允许的响应内容的最大尺寸
  maxContentLength: 2000,

  // `validateStatus` 定义对于给定的HTTP 响应状态码是 resolve 或 reject  promise 。
//如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),promise 将被 resolve; 否则,promise 将被 rejecte
validateStatus: function (status) { return status >= 200 && status < 300; // default }, // `maxRedirects` 定义在 node.js 中 follow 的最大重定向数目 // 如果设置为0,将不会 follow 任何重定向 maxRedirects: 5, // default // `socketPath` defines a UNIX Socket to be used in node.js. // e.g. '/var/run/docker.sock' to send requests to the docker daemon. // Only either `socketPath` or `proxy` can be specified. // If both are specified, `socketPath` is used. socketPath: null, // default // `httpAgent` 和 `httpsAgent` 分别在 node.js 中用于定义在执行 http 和 https 时使用的自定义代理。允许像这样配置选项: // `keepAlive` 默认没有启用 httpAgent: new http.Agent({ keepAlive: true }), httpsAgent: new https.Agent({ keepAlive: true }), // 'proxy' 定义代理服务器的主机名称和端口 // `auth` 表示 HTTP 基础验证应当用于连接代理,并提供凭据 // 这将会设置一个 `Proxy-Authorization` 头,覆写掉已有的通过使用 `header` 设置的自定义 `Proxy-Authorization` 头。 proxy: { host: '127.0.0.1', port: 9000, auth: { username: 'mikeymike', password: 'rapunz3l' } }, // `cancelToken` 指定用于取消请求的 cancel token // (查看后面的 Cancellation 这节了解更多) cancelToken: new CancelToken(function (cancel) { }) }

获取响应结果

某个请求的响包含以下信息

{
  // `data` 由服务器提供的响应
  data: {},

  // `status` 来自服务器响应的 HTTP 状态码
  status: 200,

  // `statusText` 来自服务器响应的 HTTP 状态信息
  statusText: 'OK',

  // `headers` 服务器响应的头
  headers: {},

   // `config` 是为请求提供的配置信息
  config: {},

  // 'request'  是生成此响应的请求
  //它是node.js中的最后一个 ClientRequest 实例(在重定向中)
  //和浏览器中的 XMLHttpRequest 实例
  request: {}
}

使用then,将接收下面这样的响应 

axios.get('/user/12345')
  .then(function(response) {
    console.log(response.data); //响应数据
    console.log(response.status); //http状态码
    console.log(response.statusText); //响应状态信息
    console.log(response.headers); //响应头
    console.log(response.config); //请求的配置信息
  });

配置默认值

你可以指定将被用在各个请求的配置默认值

全局的 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'; //请求头的类型

定义实例的默认值

// 创建实例时设置默认值
const instance = axios.create({
  baseURL: 'https://api.example.com'
});

// 创建实例后添加默认值
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

配置的优先顺序

配置会以一个优先顺序进行合并。这个顺序是:在 lib/defaults.js 找到的库的默认值,然后是实例的 defaults 属性,最后是请求的 config 参数。后者将优先于前者

拦截器

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

在请求拦截器中进行必要操作处理,例如添加统一cookie、请求体加验证、设置请求头等,相当于是对每个接口里相同操作的一个封装

在响应拦截器中根据响应状态码做统一的提示信息,整理响应数据等。

// 添加请求拦截器
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);
  });

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

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

可以为自定义 axios 实例添加拦截器

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

案例

在发起请求之前, 最后对要发送的请求配置对象进行修改。例如: 如果本地有token, 携带在请求头给后台,所有接口里以后暂时不用自己携带Headers+Token了,简略代码,统一管理

// 添加请求拦截器--代码实现案例:仅供参考
axios.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么, 如果vuex里有token携带在请求头中
  if (store.state.token.length > 0 && config.headers.Authorization === undefined) {
    // 发起请求之前, 把token携带在请求头上(表明自己身份)
    config.headers.Authorization = 'Bearer ' + store.state.token
  }
  return config
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error)
})

在响应回来后, 马上执行响应拦截器函数。例如: 判断是否错误401, 统一进行权限判断

// 添加响应拦截器--代码实现案例:仅供参考
axios.interceptors.response.use(function (response) { // 当状态码为2xx/3xx开头的进这里
    // 对响应数据做点什么
    return response
}, async function (error) { // 响应状态码4xx/5xx进这里
    // 对响应错误做点什么
   if (error.response.status === 401) { // 身份过期/token无效
    //  1.清空vuex的token 
    store.commit('setToken', '')
    store.commit('setRefreshToken', '')
    // 2. 清空本地token 
    localStorage.removeItem('token')
    localStorage.removeItem('refresh_token')
    //  跳转到登录页面登录
    router.push({
      path: '/login'
    })
  }     
    return Promise.reject(error)
})

错误处理

axios.get('/user/12345')
    .catch(function (error) {
        if (error.response) {
            // 请求已发出,且服务器的响应状态码超出了 2xx 范围
            console.log(error.response.data);
            console.log(error.response.status);
            console.log(error.response.headers);
        } else if (error.request) {
            // 请求已发出,但没有接收到任何响应
            // 在浏览器中,error.request 是 XMLHttpRequest 实例
            // 在 node.js 中,error.request 是 http.ClientRequest 实例
            console.log(error.request);
        } else {
            // 引发请求错误的错误信息
            console.log('Error', error.message);
        }
        console.log(error.config);
    });

可以使用 validateStatus 配置选项定义一个自定义 HTTP 状态码的错误范围。

axios.get('/user/12345', {
  validateStatus: function (status) {
    return status < 500; // Reject only if the status code is greater than or equal to 500
  }
})

取消请求

使用 cancel token 取消请求

Axios 的 cancel token API 基于cancelable promises proposal,它还处于第一阶段。

可以使用 CancelToken.source 工厂方法创建 cancel token,像这样:

const CancelToken = axios.CancelToken;
const source = CancelToken.source();

axios
  .get("/user/12345", {
    cancelToken: source.token,
  })
  .catch(function (thrown) {
    if (axios.isCancel(thrown)) {
      console.log("Request canceled", thrown.message);
    } else {
      // 处理错误
    }
  });

axios.post(
  "/user/12345",
  {
    name: "new name",
  },
  {
    cancelToken: source.token,
  }
);

// 取消请求(message 参数是可选的)
source.cancel("Operation canceled by the user.");

还可以通过传递一个 executor 函数到 CancelToken 的构造函数来创建 cancel token:

const CancelToken = axios.CancelToken;
let cancel;

axios.get("/user/12345", {
  cancelToken: new CancelToken(function executor(c) {
    // executor 函数接收一个 cancel 函数作为参数
    cancel = c;
  }),
});

// 取消请求
cancel();

注意: 可以使用同一个 cancel token 取消多个请求

更多详情请查看:http://www.axios-js.com/zh-cn/docs/

 

posted @ 2022-09-28 10:18  Lamb~  阅读(996)  评论(0编辑  收藏  举报