dong-frank的博客

Web开发基础 2024.7.22

字数统计: 834阅读时长: 3 min
2024/07/27

Web 前后端通讯及测试技术

  • 前后端交互
  • 测试
  • 实验:编写Web App 测试

后端代码结构

  • 最顶层是控制器
    • 通过注解告诉编译器会接受的请求

Http传参方法

Router Params 路由传参

基于路由的前端向后端传参

1
2
3
4
@Get("/:taskid/summary")
public async tasksummary(@Param("taskid") taskid: string){
console.log(taskid); //GET http://localhost:7001/task/233/summary
}

这些注解都是已经定义好的Interface
注意合理的路由设计,防止出现读取错误
进行必要的参数校验

Query String

查询条件
summary?state=finished

1
2
3
4
@Get("/summary")
public async summary(@Query("state") state: string){
console.log(state) //GET http://localhost:7001/task/summary?state=finished
}

问题:明文显示的参数,容易被篡改导致传参错误

Body Params

解决地址Header不可能无限长,且存在明文传参问题

1
2
3
4
5
6
7
@Post('/create')
public async create(@Body() form:{
name: string;
description: string;
}){
console.log(form); //POST http://localhost:7001/task/create
}

HTTP RESTful 接口

是一种软件架构风格

  • 资源导向 ROA 面向资源
    • 任务看板中的任务就是一种资源
    • 可以进行横向扩展(任务和用户)或纵向扩展(任务和任务的概述)
  • 无状态
  • 容易扩展

axios 前后端通信实现

基于Promise的HTTP客户端:http方法本质都是返回一个promise
axios组件:隐藏了前后端请求的实现差异,降低开发的复杂度

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import * as axios from 'axios';
const client = axios.default;
client.get('http://127.0.0.1:7001').then((response) =>{
console.log(response);
})

client.post("http://127.0.0.1:7001/task/create", {
name: "界面设计",
description:"设计敏捷看板的界面"
},
{
headers:{
'Content-Type': 'application/json'
}
}
).then((response) => {
console.log(response);
})
//无法确定哪个请求先返回结果

跨域CORS错误

前后端分离开发的常见问题:前端位于5173端口,后端位于7003端口,进行了跨域请求

解决方法

1
2
3
4
5
6
7
// src/config/config.default.ts
export default {
//...
cors:{
origin:'*',
},
}

HTTP Options:跨域的请求

Client端如何实时获取数据

Server由被动响应变为主动发送数据:http请求不具备这样的能力
方法一:while 轮询 http请求
消耗大量客户端资源

方法二:TCP长连接 WebSocket请求
请求建立一次连接,握手成功后,双方都能长时间互发数据
只要有一方断开连接,连接就会断开
WebSocket的缺点:长连接导致资源长时间被占用

具体写法见ppt

参数校验

1
2
3
4
5
if(form.name !== undefined && form.description !== undefined){
console.log(form);
}else{
console.error("Invalid form data");
}

业务逻辑代码中会充斥着大量的数据校验代码
利用框架实现自动化判断

1
2
3
4
5
6
7
8
import {Rule, RuleType} from "@midwayjs/validate";

export class TaskDto {
@Rule(RuleType.string().required())
name: string;
@Rule(RuleType.string().required())
description: string;
}

我们通常会怎么描述软件的问题

执行某个操作报错 – 功能的正确性
界面卡顿,点了没反应 – 功能,性能
功能不好用 – 易用性

前端测试Vitest

npm install -D vitest
function call

后端测试Jest

测试驱动开发
先给你测试用例,然后写程序达到通过测试用例目的

断言

见ppt

断点调试

CATALOG
  1. 1. Web 前后端通讯及测试技术
    1. 1.1. 后端代码结构
    2. 1.2. Http传参方法
      1. 1.2.1. Router Params 路由传参
      2. 1.2.2. Query String
      3. 1.2.3. Body Params
    3. 1.3. HTTP RESTful 接口
    4. 1.4. axios 前后端通信实现
      1. 1.4.1. 跨域CORS错误
    5. 1.5. Client端如何实时获取数据
    6. 1.6. 参数校验
  2. 2. 我们通常会怎么描述软件的问题
    1. 2.1. 前端测试Vitest
    2. 2.2. 后端测试Jest
    3. 2.3. 断言
    4. 2.4. 断点调试