axios 是基于Promise用于浏览器和nodejs的与服务器端通信库,支持跨平台xhrhttp请求。功能特点:支持Promise API、跨平台可在浏览器和node.js中使用、拦截请求和响应、转换请求和响应数据、取消请求、自动转换JSON数据等。
axios 安装使用
- 安装
npm i axios -S - 引入
import axios from axios1
2
3
4
5
6
7
8
9
10
11
12
13// index.vue
import axios from axios
export default {
created () {
axios.get('http://192.168.5.16:8888/category')
.then(res => { console.log(res) })
.catch(err => { console.log(err) })
axios.post('http://192.168.5.16:8888/category', {
{ type: 'sell', page:1 }
}).then(res => { console.log(res) })
.catch(err => { console.log(err) })
}
}
axios 多种请求方式 返回值为promise
axios(config)axios[method]()axios.get(url,[config])axios.post(url,[data,[config]])axios.delete(url,[config])axios.head(url,[config])axios.options(url,[config])axios.put(url,[config])axios.patch(url,[config])
axios 发送并发请求
使用axios.all([])发送多个请求,返回结果是一个数组。使用axios.spread()将返回数组展开1
2
3
4
5
6
7
8
9export default {
created () {
axios.all([axios.get('ulr1'), axios.post('url2')])
.then(axios.spread((res1, res2) => {
console.log(res1)
console.log(res2)
}))
}
}
axios 全局配置
axios.default.baseUrl = 'http://123.123.23.8:8888'设置axios的默认请求前缀地址axios.default.timeout = '30000'设置默认的请求超时时间axios.default.headers.post['Content-type'] = 'application/x-www-form-urlencode;charset=UTF-8'设置post默认请求头
axios 常见配置选项
- 请求地址
url: '/user' - 请求类型
method: 'get' - 请求根路径
baseURL: 'http://www.mt.com/api' - 请求前的数据处理
transformRequest:[function(data){}] - 请求后的数据处理
transformResponse: [function(data){}] - 自定义的请求头
headers:{'x-Requested-With':'XMLHttpRequest'} - URL查询对象
params:{ id: 12 } - 查询对象序列化函数
paramsSerializer: function(params){ } - request body
data: { key: 'aa'} - 超时设置s
timeout: 5000 - 跨域是否带Token
withCredentials: false - 自定义请求处理
adapter: function(resolve, reject, config){} - 身份验证信息
auth: { uname: '', pwd: '12'} - 响应的数据格式
responseType: 'json'
axios 拦截器与取消请求
- 请求拦截器
axios.interceptors.rquest.use(config => {}) - 响应拦截器
axios.interceptors.response.use(response => {})
*
axios 简单封装
1 | import axios from 'axios' |