个人技术总结:vue使用axios传接口参数

这个作业属于哪个课程 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格式的参数。

posted @ 2021-06-28 11:43  MEating  阅读(1656)  评论(1编辑  收藏  举报