一. axios用法
参考:
API文档: https://www.kancloud.cn/yunye/axios/234845 或者 https://axios-http.com/zh/docs/api_intro
GitHub: https://github.com/axios/axios
其它博客:https://www.jianshu.com/p/d771bbc61dab
用到的服务器端接口:

1 [Route("api/[controller]/[action]")]
2 [ApiController]
3 public class FirstController : ControllerBase
4 {
5
6 /******************************************下面是测试Get请求的相关方法***************************************************/
7
8 #region 下面是测试Get请求的相关方法
9 [HttpGet]
10 public string GetInfor1(string userName, string pwd)
11 {
12 return $"{userName}+{pwd}";
13 }
14
15 [HttpGet]
16 public string GetInfor2([FromQuery]UserInfor model)
17 {
18 return $"{model.userName}+{model.pwd}";
19 }
20 [HttpGet]
21 //加上[FromQuery]也报错
22 public string GetInfor3([FromQuery]dynamic model)
23 {
24 return $"{model.userName}+{model.pwd}";
25 }
26
27 #endregion
28
29 }
30 [Route("api/[controller]/[action]")]
31 [ApiController]
32 public class ThirdController : Controller
33 {
34 [HttpGet]
35 public IActionResult GetInfor4(string userName, string pwd)
36 {
37 return Json(new
38 {
39 userName,
40 pwd
41 });
42 }
43 }
View Code
1.简介
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。具有以下特点:从浏览器中创建 XMLHttpRequests,从 node.js 创建 http 请求,支持 Promise API,拦截请求和响应,转换请求数据和响应数据,取消请求,自动转换 JSON 数据,客户端支持防御 XSRF。
它封装了一些简易API方便快速使用,如axios.get、axios.post,也支持原始用法 axios({}),这点和JQuery还挺像的。
2.基本用法
(1). 形如axios.get().then().catch();
在then中通过 ret.data获取返回值,特别注意这里的返回值会自动转换为json,因为responseType: 'json'(默认的), 错误会进入catch,这里和fetch不一样,像400、415、500等网络错误都可以进入到catch,不需要再单独处理。
代码分享:
axios.get('https://localhost:44387/api/First/GetInfor3?userName=ypf&pwd=123456')
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
console.log(error.response.status + '---' + error.response.statusText);
});
(2).Get请求
A.用axios.get写法,可以直接在参数上拼接,也可以通过params属性写数据,当然也可附加一下额外的参数,如:headers、timeout等等。
B.用axios原始写法, 利用params传递参数,实际上和直接拼接是完全一样的,当然也可附加一下额外的参数,如:headers、timeout等等。
1 //用法1
2 // axios.get('https://localhost:44387/api/First/GetInfor1?userName=123&pwd=hhh').then(function(ret) {
3 // console.log(ret.data)
4 // });
5 //用法2
6 axios.get('https://localhost:44387/api/First/GetInfor1', {
7 params: {
8 userName: 'ypf',
9 pwd: '1234'
10 },
11 //下面是一些额外参数
12 headers: {
13 'token': 'xxsdfsdfxx'
14 },
15 timeout: 3000,
16
17 }).then(function(ret) {
18 console.log(ret.data)
19 })
20
21 //get的原始写法
22 axios({
23 method: 'get',
24 url: 'https://localhost:44387/api/First/GetInfor1',
25 params: {
26 userName: 'lisi',
27 pwd: 123
28 },
29 headers: {
30 'token': 'xxsdfsdfxx'
31 },
32 }).then(function(ret) {
33 console.log(ret.data)
34 });
(3).Post请求
PS:其中Post请求有两种,分别是: "application/x-www-form-urlencoded"表单提交的方式 和 "application/json" Json格式提交的方式。
(1). Post的表单提交的格式为:"userName=admin&pwd=123456"。
(2). Post的Json的提交格式为:将实体(类)转换成json字符串。
A.用axios.Post写法(附带传递额外参数)
a.表单提交:需要借助URLSearchParams参数进行传递。
b.JSON提交:直接拼接,即为json提交 {userName: 'lisi', pwd: 123}
//表单提交
var params = new URLSearchParams();
params.append('userName', 'zhangsan');
params.append('pwd', '111');
axios.post('https://localhost:44387/api/First/Login3', params).then(function(ret) {
console.log(ret.data)
})
//JSON提交
//默认是json格式传参的
axios.post('https://localhost:44387/api/First/Login2', {
userName: 'lisi',
pwd: 123
}).then(function(ret) {
console.log(ret.data)
})
//axios.post 传递额外参数 (json格式的提交)
axios.post('https://localhost:44387/api/First/Login2', {
userName: 'lisi',
pwd: 123
}, {
//下面是一些额外参数
headers: {
'token': 'xxsdfsdfxx'
},
timeout: 3000,
}).then(function(ret) {
console.log(ret.data)
});
B.用axios原始写法 (附带传递额外参数)
a.表单提交: 借助URLSearchParams提交; 或者在data里写,但是用transformRequest转换一下也能达到效果。
b.JSON提交: 直接在data属性里写就是JSON提交。
1 //1.原始写法 post(JSON提交)
2 axios({
3 method: 'post',
4 url: 'https://localhost:44387/api/First/Login2',
5 data: {
6 userName: 'lisi',
7 pwd: 123
8 },
9 headers: {
10 'token': 'xxsdfsdfxx'
11 },
12 }).then(function(ret) {
13 console.log(ret.data)
14 });
15
16 //2. 原始写法 post(表单提交)用法1
17 var params = new URLSearchParams();
18 params.append('userName', 'zhangsan');
19 params.append('pwd', '111');
20 axios({
21 method: 'post',
22 url: 'https://localhost:44387/api/First/Login3',
23 data:params,
24 headers: {
25 'token': 'xxsdfsdfxx'
26 },
27 }).then(function(ret) {
28 console.log(ret.data)
29 });
30
31 //3. 原始写法 post(表单提交) 用法2
32 axios({
33 method: 'post',
34 url: 'https://localhost:44387/api/First/Login3',
35 //允许在向服务器发送前,修改请求数据
36 transformRequest: [function(data) {
37 let ret = ''
38 for (let it in data) {
39 ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
40 }
41 return ret;
42 }],
43 data: {
44 userName: 'lisi',
45 pwd: 123
46 },
47 headers: {
48 'token': 'xxsdfsdfxx',
49 'Content-Type': 'application/x-www-form-urlencoded'
50 },
51 }).then(function(ret) {
52 console.log(ret.data)
53 });
4. 其它详细配置
这里只分析几个常用的,其它的详见上面的Api文档。
(1).url: 用于请求URL
(2).method: 请求方式,默认为get请求
(3).params: 用于向URL上拼接地址,和直接在地址上拼接效果一样,用于get请求
(4).data:作为请求主体被发送的数据,多用于POST请求
(5).headers:请求表头
(6).timeout:请求超时时间,单位毫秒
(7).withCredentials:表示跨域请求时是否需要使用凭证,默认是false
(8).responseType:表示服务器响应的数据类型,可以是 'arraybuffer', 'blob', 'document', 'json'(默认), 'text', 'stream'
(9).baseURL: 拼接在url的前面
(10).transformRequest: 允许在向服务器发送前,修改请求数据
(11).transformResponse: 在传递给 then/catch 前,允许修改响应数据
5.全局默认设置
全局配置baseUrl、全局配置Header、全局配置过期时间等等。
1 // 配置请求的基准URL地址
2 axios.defaults.baseURL = 'https://localhost:44387';
3 // 配置请求头信息
4 axios.defaults.headers['mytoken'] = 'hello';
5 axios.get('/api/First/GetInfor1', {
6 params: {
7 userName: 'ypf',
8 pwd: '1234'
9 },
10 }).then(function(ret) {
11 console.log(ret.data)
12 })
6. 拦截器
(1).可以在请求发送前拦截,比如添加header。
(2).在响应后进行拦截,比如返回: ret.data(), 后面就可以直接用了。
1 //请求前拦截
2 axios.interceptors.request.use(function(config) {
3 // console.log(config.url)
4 config.headers.mytoken = 'nihao'; //设置一下header
5 return config;
6 }, function(err) {
7 console.log(err)
8 });
9 //响应后拦截
10 axios.interceptors.response.use(function(res) {
11 var data = res.data;
12 return data;
13 }, function(err) {
14 console.log(err)
15 });
16 //这样这里可以直接使用data了
17 axios.get('https://localhost:44387/api/First/GetInfor1', {
18 params: {
19 userName: 'ypf',
20 pwd: '1234'
21 },
22 }).then(function(data) {
23 console.log(data)
24 });
7. 其它用法补充: 取消请求和并发请求
详见Api文档。 axios.all(iterable) axios.all(iterable)
二. async异步编程
1.async作为一个关键字放到函数前面,任何一个 async 函数都会隐式返回一个 promise。
2.await 关键字只能在使用 async 定义的函数中使用,后面可以直接跟一个 Promise实例对象,await函数不能单独使用。
3.async/await 让异步代码看起来、表现起来更像同步代码。
1 var vm = new Vue({
2 el: '#myApp2',
3 methods: {
4 handle1: async function() {
5 var ret1 = await axios.get('https://localhost:44387/api/Third/GetInfor4?userName=ypf&pwd=123456');
6 var userName = ret1.data.userName;
7 var pwd = ret1.data.pwd;
8 //可以直接在后面捕捉错误
9 var ret2 = await axios.post('https://localhost:44387/api/First/Login2', {
10 userName: userName+'001',
11 pwd: pwd+'001'
12 }).catch(error=>{
13 console.log(error);
14
15 });
16 // console.log(ret2.data);
17 return ret2.data;
18 }
19 }
20 });
!
- 作 者 : Yaopengfei(姚鹏飞)
- 博客地址 : http://www.cnblogs.com/yaopengfei/
- 声 明1 : 如有错误,欢迎讨论,请勿谩骂^_^。
- 声 明2 : 原创博客请在转载时保留原文链接或在文章开头加上本人博客地址,否则保留追究法律责任的权利。