Resume全栈项目(二)(.React+Ts)
文章目录
- 项目地址
- 一、前端获取后端Api
- 1.1 读取Campany列表
- 1. 创建统一后端接口
- 2. 封装axios请求
- 3. 创建接口文档
- 4. 前端读取数据
- 1.2 添加Company
- 1. 添加CreateCompany的interface
- 2. 添加页面
项目地址
- 教程作者:
- 教程地址:
- 代码仓库地址:
- 所用到的框架和插件:
dbt
airflow
一、前端获取后端Api
1.1 读取Campany列表
1. 创建统一后端接口
📂 src
┣ 📂 constants
┃ ┗ 📄 url.constants.ts
- src里创建
constants
文件夹,添加url.constans.ts
用来存放baseUrl
export const baseUrl = "https://localhost:7129/api";
2. 封装axios请求
- 封装了 Axios HTTP 客户端,用于简化 API 请求,并且可以统一设置基础 URL、超时时间、请求头等配置
http.module.ts
import axios from "axios";
import { baseUrl } from "../constants/url.constants";
const httpModule = axios.create({
baseURL: baseUrl,
timeout: 5000, // 5秒超时
headers: { "Content-Type": "application/json" }
});
export default httpModule;
3. 创建接口文档
📂 src
┣ 📂 types
┃ ┣ 📄 company.types.ts
┃ ┣ 📄 job.types.ts
┃ ┗ 📄 index.ts
company.types.ts
用来处理company页面相关的接口
export interface ICompany {
id: string;
name: string;
size: string;
createdAt: string;
}
export interface ICreateCompanyDto {
name: string;
size: string;
}
4. 前端读取数据
- 使用useEffect读取后端数据
const Companies = () => {
const [companies, setCompanies] = useState<ICompany[]>([]);
const [loading, setLoading] = useState<boolean>(false);
const redirect = useNavigate();
useEffect(() => {
setLoading(true);
httpModule
.get<ICompany[]>("/Company/Get")
.then((response) => {
setCompanies(response.data);
setLoading(false);
})
.catch((error) => {
alert("Error");
console.log(error);
setLoading(false);
});
}, []);
// console.log(companies);
return (
<div className="content comapnies">
<div className="heading">
<h2>Companies</h2>
<Button variant="outlined" onClick={() => redirect("/companies/add")}>
<Add />
</Button>
</div>
{loading ? (
<CircularProgress size={100} />
) : companies.length === 0 ? (
<h1>No Company</h1>
) : (
<CompaniesGrid data={companies} />
)}
</div>
);
};
export default Companies;
1.2 添加Company
1. 添加CreateCompany的interface
- 创建company的interfrace
export interface ICreateCompanyDto {
name: string;
size: string;
}
2. 添加页面
- 设置表单存储的state
const [company, setCompany] = useState<ICreateCompanyDto>({ name: "", size: "" });
- 获取表单数据
3. 将表单数据提交