Axios


title: Axios

date: 2019-09-24 11:33:48

tags:  # 这里写的分类会自动汇集到 categories 页面上,分类可以多级

  • HTML # 一级分类
  • HTTP进阶 # 二级分类

Axios

axios 是一个基于 Promise 用于浏览器和 nodejs 的 HTTP 客户端,它本身具有以下特征:

  • 从浏览器中创建 XMLHttpRequest
  • 从 node.js 发出 http 请求
  • 支持  Promise API 拦截请求和响应
  • 转换请求和响应数据
  • 取消请求
  • 自动转换 JSON 数据
  • 客户端支持防止  CSRF/XSRF

步骤:

  1. 安装

$ npm install axios

或者 CDN 引入 2. 引入 3. 一般是把 axios 挂载到原型上,便于全局使用

1
Vue.prototype.$http = axios;

Axios 之 get 请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
methods: {
getData(){
this.$http.get('https://cnode.js.org/api/v1/topic',{
params: {
page: 1,
limit: 10
}
})
.then(res=>{
this.items = res.data.data
})
.catch(err=>{
console.log(err)
})
}
}
1
2
3
4
5
6
7
8
9
10
11
12
//上面get请求的其他写法
axios.get("/user", {
params: {
ID: 12345,
},
});
//如果只有一个选项
axios.get("/user", {
ID: 12345,
});
//将数据写到url里
axios.get("/user?page=1&limit=10");

Axios 之 post 请求

1
2
3
4
5
6
7
8
9
10
11
axios
.post("/user", {
firstName: "tom",
lastName: "green",
})
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
});

POST 传递参数有两种格式:

  • form­-data  格式: ?page=1&limit=48.但是不能写在 url 里
  • x-­www-­form-­urlencoded 格式: { page: 1,limit: 10 }

在 axios 中,post 请求接收的参数必须是 form-­data

可以使用 qs 插件—­qs.stringify

执行多个并发请求

1
2
3
4
5
6
7
8
9
10
11
12
13
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) {
// 两个请求现在都执行完成
})
);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
postData(){
//先要安装qs插件,然后引入
//使用qs插件将对象格式转化为form-data格式
this.$http.post(url,qs.stringify({
page: 1,
limit: 10
}))
.then(res=>{
console.log(res)
})
.catch(err=>{
console.log(err)
})
}

拦截器 interceptors

在请求或响应被 then 或 catch 处理前拦截它们。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// 添加请求拦截器
axios.interceptors.request.use(
function (config) {
// 在发送请求之前做些什么
return config;
},
function (error) {
// 对请求错误做些什么
return Promise.reject(error);
}
);

// 添加响应拦截器
axios.interceptors.response.use(
function (response) {
// 对响应数据做点什么
return response;
},
function (error) {
// 对响应错误做点什么
return Promise.reject(error);
}
);

如果你想在稍后移除拦截器,可以这样:

1
2
3
4
var myInterceptor = axios.interceptors.request.use(function () {
/*...*/
});
axios.interceptors.request.eject(myInterceptor);

可以为自定义 axios 实例添加拦截器

1
2
3
4
var instance = axios.create();
instance.interceptors.request.use(function () {
/*...*/
});