Axios是什么?

Axios 是一个基于 promise 网络请求库,作用于node.js 和浏览器中。 它是 isomorphic 的(即同一套代码可以运行在浏览器和node.js中)。在服务端它使用原生 node.js http 模块, 而在客户端 (浏览端) 则使用 XMLHttpRequests。

主要功能

  • 从浏览器创建 XMLHttpRequests
  • 自动转换JSON数据
  • 拦截请求和响应
    ps: Axios功能很多详情请见官网(文末贴出)

基本使用

  1. 发送get请求
1
2
3
4
5
6
7
8
9
10
11
12
13
14
axios.get('http://user/account/info',{
headers: {
//添加请求参数
params: {
userId:5,
},
//添加token
Authorization: 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOjEsImV4cGlyZV90aW1lIjoxNzI5NjkyMjk4ODgxfQ.c1COcBtlB1NWQumOBbb_Dlvo-lX13jgDI4hIliQO6JI'
}
}).then(resp => {
console.log('success:'+ JSON.stringify(resp.data));
}).catch(error => {
console.log('error:'+ JSON.stringify(error));
});

参数:

  • url: 访问路径
  • config: 配置请求属性.例如:设置headers
  1. 发送post请求
1
2
3
4
5
6
7
8
9
10
11
12
Axios.post("http://user/account/token",{
username: "celestrong",
password: "123456"
},{
headers: {
ContentType: "appliaction/json"
}
}).then(resp =>{
console.log(" success:"+JSON.stringify(resp.data));
}).catch(error => {
console.log("error:"+JSON.stringify(error));
});

参数:

  • url: 访问路径
  • data: 请求数据
  • config: 配置请求参数

Axios配置

  1. 设置baseUrl(main.js中)
1
axios.defaults.daseURL="http://localhost:3000"

axios官网: https://www.axios-http.cn/