前端项目中接口实现

547 阅读1分钟

本篇文章基于 前后端完全分离,服务端只提供HTTP API,前端通过Ajax与服务端进行通信

为公司实习中遇到的后台管理系统中遇到的接口使用的总结。

1.从models文件夹中写最基本的,state中需要定义引用的数据,并引入

state中就直接写定义的接口

需要通过get post发送请求来获取的在service文件夹下写接口,且写为函数,通过在主代码中用函数调用

  async postActivityNew(row: ActivityItem) {
    try {
      tt.verify(!!row.desc, "NotFound", "描述不能为空")
      tt.verify(!!row.subject, "NotFound", "名字不能为空")
      let res = await BookAc.postActivityNew(row.subject, row.desc)
      tt.check(res)
      this.setState({
        isAdd: false,
        editingKey: -1
      })
      this.getActivityList()
    } catch (e) {
      toast.catchError(e)
    }
  }

service文件夹中定义接口

export function postActivityNew (desc: string,subject: string) {
    return http.post<NewActivityResponse>('/**/api/**/activity/new', {
      desc,
      subject
    })
  }

其中NewActivityResponse接口又需要再去models文件夹中定义。

export interface NewActivityResponse extends BaseResponse {
  desc: string
  subject: string
}

接口对应数据如果有问号?代表该数据可选 , 别的页面也可以引用这个接口中定义的部分数据。