VUE中使用HTTP库Axios方法详解

2020-06-16 06:44:21易采站长站整理

Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中

安装Axios模块

在Vue中使用,最好安装两个模块axios 和vue-axios


$npm install axios vue-axios --save

然后引用并使用模块


import Axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios,Axios)

在组件中通过如下方式进行使用


this.$http[method]()

Axios模块特性

1、可以从浏览器中创建XHR对象

2、可以从nodeJS中创建HTTP请求

3、支持Promise API 

4、可以拦截请求和响应

5、可以转换请求数据和响应数据

6、可以取消请求

7、可以自动转换JSON数据

8、客户端支持防御XSRF

Vue下使用使用Axios

下面是一些简单的请求实例

get请求

仅仅向后端请求数据


axios.get('index.php')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

通过URL向后端发送数据,要使用params属性,params属性包含即将与请求一起发送的数据

运行下列代码后,请求URL变更为index.php?id=12345&text=%E5%B0%8F%E7%81%AB%E6%9F%B4


axios.get('index.php',{
params:{
id:12345,
text:'jb51'
}
}).then((response)=>{
console.log(response)
}).catch((error)=>{
console.log(error)
})

当然,也可以把数据直接写到URL中


// 为给定 ID 的 user 创建请求
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

post请求

一般来说,post请求更多的是要提交数据,params属性里的数据会出现在请求主体中

[注意]如果是axios.create()方法中的params属性,则其里面的数据会出现在URL参数中

但实际上,post方法不需要使用params属性,它的第二个参数就是要发送的数据


axios.post('index.php',{
id:12345,
text:'jb51'
}).then((response)=>{
console.log(response)
}).catch((error)=>{
console.log(error)
})

多并发请求


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) {
// acct为第一个请求的结果,perms为第二个请求的结果