一. 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 : 原創部落格請在轉載時保留原文連結或在文章開頭加上本人部落格位址,否則保留追究法律責任的權利。