| 這個作業屬於哪個課程 | 2021春軟件工程實踐S班 |
|---|---|
| 這個作業要求在哪里 | 軟件工程總結&個人技術博客 |
| 這個作業的目標 | |
| 其他參考文獻 | .... |
PART 1 技術概述
vue2.0版本推薦使用axios來完成ajax請求。
在使用axios連接前后端接口時,接口要求的參數格式不同,相應的代碼也不同。
PART 2 技術詳述
因為我在連接口的時候被不同形式的參數搞暈過,所以想着記錄一下實踐過程中遇到的不同格式的接口傳遞參數。
首先,在main.js中導入axios和qs
qs的作用可以看npm qs模塊
import axios from 'axios'
import qs from 'qs'
Vue.prototype.$axios = axios; //全局注冊,使用方法:this.$axios
Vue.prototype.$qs=qs;
根據不同接口的參數格式要求寫不同的傳遞參數方式
EXP1
接口1
請求URL http://xx.com/add/
請求方式:POST
參數
| 參數名 | 必選 | 類型 | 說明 |
|---|---|---|---|
| uid | 是 | string | 用戶ID |
| name | 是 | string | 用戶名 |
| password | 是 | string | 密碼 |
| role | 否 | int | 角色 |
返回示例
{
code:0,
data:{
"uid": "123456",
"name": "123",
"password": "12345678",
"role": 0
}
}
接口1要求傳過去的參數是json結構體的形式,axios連接的代碼:
this.$axios
.post('http://xx.com/add',this.$qs.stringify({
'uid':123456,
'name':iu,
'password':9876544,
'role':1
})
)
.then(res=>{
//res保存了返回的數據
console.log(res.data.code)
})
EXP2
接口2
請求URL:http://xx.com/api/v1/user/:id
請求方式:GET
參數:url參數
返回示例
{
"code": 0,
"data": {
"uid": "221801101",
"user_name": "黃志軍",
"pair_uid": "221801102",
"pair_name": "林蒼涼",
"team_id": 0,
"class_id": 1,
"role": 0
},
"msg": ""
}
接口2要求使用url參數,axios連接的代碼
this.$axios
.get('http://xx.com/api/v1/user/'+userid)
.then(res=>{
console.log(res.data.code)
})
EXP3
接口3
請求URL:http://xx.com/api/v1/homework/list?{class_id=}&{page=}
請求方式:GET
參數
| 參數名 | 必選 | 類型 | 說明 |
|---|---|---|---|
| class_id | 是 | URL參數,int | 班級id |
| page | 否 | URL參數,int | 分頁 |
返回示例
{
"code":0,
"data":{
"total_page":1,
"current_page":1,
"list":[
{
"title":"",
"start_time":"",
"end_time":""
},
{
"title":"",
"start_time":"",
"end_time":""
}
]
}
}
接口3和接口2相似,只是傳遞的參數變成了2個,axios連接的代碼
this.$axios
.get('http://xx.com/api/v1/homework/list?class_id='+classID+'&page='+page)
.then(res=>{
console.log(res.data.code)
})
PART 3 總結
分清url參數和json格式的參數。
