学习目标:
了解 axios
学习内容:
axios的作用及包含的方法
学习笔记:
- 1、axios 是什么?
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。主要用于向后台发送请求。 - 2、axios 的作用
主要用于向后台发送请求。 - 3、axios 的特点
(1)、从 node.js 创建http 请求
(2)、转换请求数据和响应数据
(3)、自动转换json数据
(4)、拦截请求和响应
(5)、支持Promise API
(6)、 从浏览器中创建XMLHttpRequests
(7)、取消请求
(8)、客户端支持防御XSRF - 4、若使用 npm 时,首先需要 安装 axios
npm install axios
- 5、axios 可以发送post请求 , 也可以发送 get 请求
(1)、post 请求
this.$axios.post(this.mixinViewModuleOptions.updateURL, this.dataForm)
this.$axios.post("/sys/dept/company_select", {})
上述几种都可后面添加
.then((response) => {
console.log(response)
})
.catch((error) => {
console.log(error);
});
(2)、get 请求
//指定请求的 url
getRoleList () {
return this.$axios.get('/sys/role/select').then(res => {
this.roleList = res
}).catch(() => {})
},
//直接可以将id 拼接到请求的url上
this.$axios.get('/device/qiuguan/info_by_device_id/' + this.deviceId).then(res => {
this.dataInfo.name= res.name
}).catch(() => {})
//将参数的值一并发送到后端
axios.get('/sys/user',{params:{ ID:321}})
上述都可以后面添加
.then(res => {
console.log(res)
this.dataForm = res.repair;
}
}).catch(() => {})
(3)、了解到 axios 还可以一次性并发多个请求(此功能自己在项目中还未使用,在此先记录下来)
function getDept(){
return axios.get('/sys/dept');
}
function getDeptPermissions(){
return axios.get('/sys/dept/123');
}
axios.all([getDept(),getDeptPermissions()])
.then(axios.spread(function(acct,perms){
console.log(acct)
console.log(perms)
}))
注:当这两个请求都完成的时候,会触发这个函数,其中acct,perms 两个参数分别代表返回的结果。
本篇初步了解下 axios 的作用及 常用的 请求方式,下篇我们进一步了解 axios 的相关内容。