axios是一个可以向后台发送交互数据请求并基于 promise 的HTTP库,可以用在浏览器和 node.js 中(与ajax功能类似)
特点:
从浏览器中创建 XMLHttpRequests
从 node.js 创建 http 请求
支持 Promise API
拦截请求和响应
转换请求数据和响应数据
取消请求
自动转换 JSON 数据
客户端支持防御 XSRF
axios使用示例(get、delete、head、post、put和patch使用方法雷同):
Vue.prototype.$axios = axios
this.$axios.get('/user', {params: {ID: 12345}}) //get请求,可以直接使用get('/user?ID=12345')方法
.then(function (response) {...}) //请求成功之后调用,可以定义多个then方法,按定义顺序执行
.catch(function (error) {...}) //请求失败之后调用
this.$axios({ //该方法可选参数较多,只例举常用参数(URL参数必填)
url: '/user/12345', //请求服务器路径(必填)
method: 'post', //请求方法(默认get)
data: {test: '测试数据'}, //作为请求主体被发送的数据
params: {name: 'TT'}, //作为与请求一起发送的URL的参数(URL?name='TT')
responseType: 'json', //服务器响应的数据类型
headers: {'X-Requested-With': 'XMLHttpRequest'} //自定义请求头
})
var dataRequ = this.$axios.interceptors.request.use( //请求拦截器
function (config) {...}, //发送请求之前调用
function (error) {...} //请求失败调用
)
var dataResp = this.$axios.interceptors.response.use( //响应拦截器
function (config) {...}, //响应数据之前调用
function (error) {...} //响应失败调用
)
this.$axios.interceptors.request.eject(dataRequ); //注消请求拦截器
this.$axios.interceptors.request.eject(dataResp); //注消响应拦截器