axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。它主要是用于向后台发起请求的,还有在请求中做更多是可控功能。vue-axios 是 axios 集成到 Vue.js 的小包装器。
1、axios 和 vue-axios 的安装和引入
(1)采用 npm 的方式进行安装,在终端输入下面命令安装下载 axios 和 vue-axios 依赖:
npm install --save axios vue-axios
(2)在src/main.js入口文件中导入 axios 和 vue-axios依赖:
import axios from 'axios';
import VueAxios from 'vue-axios';
Vue.use(VueAxios,axios);
2、axios 和 vue-axios 的使用
axios的请求方法:
(1)get:获取数据;
(2)post:提交数据,表单提交和文件上传;
(3)put:更新数据,所有数据推送到后端;
(4)patch:更新数据,只将修改的数据推送到后端;
(5)delete:删除数据。
使用方式:
注意:使用 vue-axios 更符合vue整体的生态环境,直接写原型链会有些粗暴,并且直接写原型链要取名为$http,多人合作的情况下,其他项目成员可能取另外的名字,维护起来比较麻烦,而统一使用 vue-axios 就没有太多歧义。
(1)方式一:
Vue.axios.get(api).then((response) => {
console.log(response.data)
})
(2)方式二:
this.axios.get(api).then((response) => {
console.log(response.data)
})
(3)方式三:
this.$http.get(api).then((response) => {
console.log(response.data)
})
发送GET请求:
axios封装了get方法,传入请求地址和请求参数,就可以了,同样支持Promise。
(1)不带参数的GET请求 :
this.$axios
.get(url)
.then((response) =>
console.log(response) //返回的数据
})
.catch((error) => {
console.log(error) //错误信息
})
(2)带参数的GET请求:
this.$axios.get(url, {
params: {
id: 1
}
})
.then((response) => {
console.log(response) //返回的数据
})
.catch((error) => {
console.log(error) //错误信息
})
发送POST请求:
与发送GET请求相似,但是带参数的POST请求的参数不需要写在params属性下。
(1)不带参数的POST请求:
this.$axios
.post(url)
.then((response) =>
console.log(response) //返回的数据
})
.catch((error) => {
console.log(error) //错误信息
})
(2)带参数的POST请求:
let data = {
id: 1
}
this.$axios
.post(url, data)
.then((response) => {
console.log(response) //返回的数据
})
.catch((error) => {
console.log(error) //错误信息
})
拦截器:
(1)请求拦截器:
请求拦截器的作用是在请求发送前进行一些操作,例如在每个请求体里加上token,统一做了处理如果以后要改也非常容易,代码如下:
// 添加请求拦截器
axios.interceptors
.request
.use(function (config) {
// 在发送请求之前做些什么
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});
(2)响应拦截器:
响应拦截器的作用是在接收到响应后进行一些操作,例如在服务器返回登录状态失效,需要重新登录的时候,跳转到登录页,代码如下:
// 添加响应拦截器
axios.interceptors
.response
.use(function (response) {
// 对响应数据做点什么
return response;
}, function (error) {
// 对响应错误做点什么
return Promise.reject(error);
});