axios的安装和使用

在这里插入图片描述

一、axios介绍

什么是 axios?
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
特性:
1、从浏览器中创建 XMLHttpRequests
2、从 node.js 创建 http 请求
3、支持 Promise API
4、拦截请求和响应
5、转换请求数据和响应数据
6、取消请求
7、自动转换 JSON 数据
8、客户端支持防御 XSRF

浏览器支持:
在这里插入图片描述

二、安装axios

  1. 方法一:速度慢
npm install axios -g
  1. 方法二:速度快
cnpm install axios -g

参数说明:
-g:表示全局安装,将会安装在你配置的:C:\Users\XinLiu\nodejs\node_global目录下。如果不指定则为当前文件夹所在目录(局部);

安装成功后如下所示:

在这里插入图片描述
3. 无需安装,直接使用cdn

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

三、 案例

  1. 执行 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);
  });
  1. 执行 POST 请求
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

  1. 执行多个并发请求
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) {
    // 两个请求现在都执行完成
  }));

四、框架整合

1、整合vue-axios

基于vuejs 的轻度封装

1.1 安装vue-axios

cnpm install --save axios vue-axios -g //-g:全局安装

1.2 将下面代码加入入口文件:

import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(VueAxios, axios)

按照这个顺序分别引入这三个文件: vue, axios and vue-axios

1.3 你可以按照以下方式使用:

Vue.axios.get(api).then((response) => {
  console.log(response.data)
})

this.axios.get(api).then((response) => {
  console.log(response.data)
})

this.$http.get(api).then((response) => {
  console.log(response.data)
})

五、插件

  1. axios-retry

Axios 插件 重试失败的请求

1.1 安装

cnpm install axios-retry -g //-g:全局安装

1.2 使用

// CommonJS
// const axiosRetry = require('axios-retry');

// ES6
import axiosRetry from 'axios-retry';

axiosRetry(axios, { retries: 3 });

axios.get('http://example.com/test') // The first request fails and the second returns 'ok'
  .then(result => {
    result.data; // 'ok'
  });

// Exponential back-off retry delay between requests
axiosRetry(axios, { retryDelay: axiosRetry.exponentialDelay});

// Custom retry delay
axiosRetry(axios, { retryDelay: (retryCount) => {
  return retryCount * 1000;
}});

// 自定义 axios 实例
const client = axios.create({ baseURL: 'http://example.com' });
axiosRetry(client, { retries: 3 });

client.get('/test') // 第一次请求失败,第二次成功
  .then(result => {
    result.data; // 'ok'
  });

// 允许 request-specific 配置
client
  .get('/test', {
    'axios-retry': {
      retries: 0
    }
  })
  .catch(error => { // The first request fails
    error !== undefined
  });

注意:除非 shouldResetTimeout被设置, 这个插件将请求超时解释为全局值, 不是针对每一个请求,二是全局的设置。

1.3 测试
克隆这个仓库 然后 执行:

cnpm test
  1. vue-axios-plugin

Vuejs 项目的 axios 插件

2.1 安装

可以通过script标签引入,无需安装:

<!-- 在 vue.js 之后引入 -->
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vue-axios-plugin"></script>
cnpm install --save vue-axios-plugin -g //-g:全局安装

然后在入口文件配置如下:

import Vue from 'Vue'
import VueAxiosPlugin from 'vue-axios-plugin'

Vue.use(VueAxiosPlugin, {
  // 请求拦截处理
  reqHandleFunc: config => config,
  reqErrorFunc: error => Promise.reject(error),
  // 响应拦截处理
  resHandleFunc: response => response,
  resErrorFunc: error => Promise.reject(error)
})

2.2 示例
在 Vue 组件上添加了 $http 属性, 它默认提供 get 和 post 方法,使用如下:

this.$http.get(url, data, options).then((response) => {
  console.log(response)
})
this.$http.post(url, data, options).then((response) => {
  console.log(response)
})

你也可以通过 this.$axios 来使用 axios 所有的 api 方法,如下:

this.$axios.get(url, data, options).then((response) => {
  console.log(response)
})

this.$axios.post(url, data, options).then((response) => {
  console.log(response)
})
  • 29
    点赞
  • 139
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

星牛君

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值