axios的使用与二次封装

axios是什么?

要使用axios首先要明白它是什么?有何用?

  1. axios是基于promise用于浏览器和node.js是http客户端,本质上也是对原生XHR的封装,只不过它是Promise的实现版本,符合最新的ES规范。简单来说就是一个promise语法的Ajax请求库。
  2. axios的作用主要是用于向后台发起请求的,还有在请求中做更多是可控功能。

axios特性

市场上有这么多的类似功能的,为何我们要选择axios,主要是axios有以下特性:

  • 从浏览器中创建 XMLHttpRequests
  • 从 node.js 创建 http 请求
  • 支持 Promise API
  • 拦截请求和响应
  • 转换请求数据和响应数据
  • 取消请求
  • 自动转换 JSON 数据
  • 客户端支持防御 XSRF

axios安装

既然axios如此好用,那么如何安装
使用npm

$ npm install axios

使用yarn

$ yarn add axios

使用cdn

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

axios的初步使用

如果是简单的get/post请求可以直接使用axios的方法

get请求
// 没有参数的get请求
axios.get('http://127.0.0.1:3000/users').then(res => {
   console.log(res)
}).catch(function (err) {
    console.log(err)	// 做一个错误捕获
})

// 以 / 方式携带参数的get请求
axios.get('http://127.0.0.1:3000/users/1').then(res => {
	console.log(res) // 可以直接将参数写在对应的位置
}).catch(function (err) {
    console.log(err)
})

// 以 ? 方式携带参数的get请求
// 方式一: 可以和上面一样把参数写在对应的位置
axios.get('http://127.0.0.1:3000/users/unane=aaa').then(res => {
	console.log(res)
}).catch(function (err) {
    console.log(err)
})
// 方式二: 可以在后面写一个params,里面写要传递的参数
axios.get('http://127.0.0.1:3000/users', { params: {id: 1}}).then( res => {
	console.log(res)
}).catch(function (err) {
    console.log(err)
})
post请求
// post请求
axios.post('http://127.0.0.1:3000/users', { uname: 'aabb', uage: 18 }).then(res => {
	 console.log(res)	// 在接口后面直接写一个{},在里面写入传递的参数
}).catch(function (err) {
    console.log(err)
})
处理多个并发请求
function getUsera() {
  return axios.get('http://127.0.0.1:3000/users/a')
}

function getUserb() {
  return axios.get('http://127.0.0.1:3000/users/b')
}

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

axios的完整写法

当你需要设置请求头或者其他的参数时候,这时候就要用到axios的完整形式

axios({
      url: 'http://127.0.0.1:3000/users',	// 请求的路径
      method: 'get',	// 请求方式
      headers: {	// 配置请求头
        /* 在配置请求头,一些特殊字段 */
      },
      data: {	// 设置请求的参数
    	name: 'aabb',
    	age: '18'
  		}
    }).then((res) => {
      console.log(res)
    })

axios的二次封装

众所周知axios是一个对于Ajax的封装,当你要频繁的访问数据时候哈可以把axios二次封装

import axios from 'axios'	// 导入axios
const instance = axios.create({
  baseURL: 'https://127.0.0.1',	 // 请求地址 
  method: 'get',
  timeout: 10000,	// 请求超时
  headers: {
    'X-Info': '{"a":"123","b":"456","c":"789"}'
  },
  params: {		
    id: 12345
  },
  responseType: 'json',  // 相应的数据类型
})
export default instance		// 导出封装好的axios

// 下次使用时候直接导入封装好的文件
import http from './http'
http.request({
      url: '/user',
      headers: {
        'X-Host': 'abc.a-b.info'
      }
 }).then(res => {
      console.log(res)
 })

更多可以见axios官方文档

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值