axios的用法详解

axios: 是一个类库,基于Promise管理的Ajax库,支持浏览器和nodejs的http库,常用于Ajax请求。

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

安装方法

使用 npm:

$ npm install axios

使用 bower:

$ bower install axios

使用 cdn:

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

axios提供了多种请求方式,比如直接发起get或post请求:

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

在get请求中的键值对拼接成URLENCODED式的字符串然后1以问号传递参数的方式,传递给服务器。

执行post请求

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

基于Promise,可以执行多个并发请求:

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) {
    // 请求现在都执行完成时
  }));

也可以通过写入配置的形式发起请求:
axios(config)

// 发送 POST 请求
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
})
	.then(function(res) {
	console.log(res)
	});

在业务中,经常将其封装成为实例的形式调用,便于做通用配置,
例如:

//util.js
const instance = axios.create({
	baseURL: 'http://some-domain.com/api',
	timeout: 1000,
	header: {
	'Content-Type': 'application/x-www-form-urlencoded'
	}
}) 

export default instance

index.js

<tempalte>
	<div></div>
</template>
<script>
	import Ajax from './util.js'
	export default {
	created(): {
		 Ajax ( {
			method: 'post',
			url: '/user',
			  data: {
					    firstName: 'Fred',
					    lastName: 'Flintstone'
					  }
		}).then(res => {
			console.log(res)
		})
		}
	}
</script>

请求方法的别名

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

标注: 在使用别名方法时, url、method、data 这些属性都不必在配置中指定。

并发

处理并发请求的助手函数

axios.all(iterable)
axios.spread(callback)

创建实例
可以使用自定义配置新建一个 axios 实例

axios.create([config])

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

更多关于axios的配置请参考: https://www.kancloud.cn/yunye/axios/234845

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

前端岚枫

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

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

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

打赏作者

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

抵扣说明:

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

余额充值