简单编写前端接口
前言
由于没有接触过前后端开发,在最近跟的项目中涉及的部分较少,但是仍然要积极尝试更多东西,前端接口的编写是我涉及的一部分,记录关键步骤便于以后回顾和使用,以下内容展示关键步骤供参考,具体需要根据实际项目来编写。有错误的地方欢迎大家评论区指出。
范例一:根据学生学号stuId获得学生课程信息
1.向后端说明该接口的需求
Request Example:
url: ' /api/getStuinfo',
method: 'get',
data: {
course: ' '//课程信息
}
2.编写接口调用函数
虽然在接口需求中写了url,但实际的url是根据后端提供的来写。
import request from "/router/axios";
//根据stuId返回学生课程信息
export const getCourse= (stuId) => {
return request({
url: '/api/course/getStuCourseBystuId',//后端接口地址
method: 'get',
params:{
stuId,//前端传参,向后端发送学生学号,获取学生课程信息
}
})
}
3.导入并调用接口函数
<script>
import {getCourse} from "function-path";//该路径为getCourse函数的路径
export default {
name: "course" ,
props:{
values:{
type: Array ,//根据后端返回的course信息查看信息类型,String or Array or...
default: function(){
return []
}
}
},
data() {
return {
courseList:[]//对应上面的类型Array
};
},
created() {
getCourse('110').then(res => {
console.log(res)//res为响应对象,在控制台可以输出查看包含的数据
this.courseList=res.data.data//把响应的数据赋给组件的变量
console.log(this.courseList[0].courseName)//打印查看课程名
//courseList是数组,要指定序列courseList[0],否则查看不到信息
})
}
};
</script>
4.展示课程信息
<template>
<tr>
<td>课程名:</td>
<td>{{courseList[0].courseName}}</td>
</tr>
<tr>
<td>课程时长:</td>
<td>{{courseList[0].courseTime}}</td>
</tr>
</template>