You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot+React TS项目员工表单提交无响应问题求助

员工表单提交无反应问题排查与解决

问题背景

我是全栈开发新手,搭建了Spring Boot后端+React TypeScript前端的全栈项目,已创建Company和Employee两个实体及对应DTO。公司表单可成功提交新记录,但员工表单提交新员工信息时无任何反应,怀疑问题出在实体的序列化与反序列化环节,附上项目代码寻求解决方法。


后端代码问题修正

1. 移除DTO中的JPA注解

EmployeeDTO中错误使用了@ManyToOne这类JPA实体注解,DTO仅需定义数据传输字段,该注解会引入懒加载代理对象,导致序列化失败。

修改后的EmployeeDTO:

@Data
public class EmployeeDTO implements Serializable {
    Long id;

    @Size(max = 255)
    String name;

    @Size(max = 255)
    String surName;

    @Size(max = 255)
    String email;

    LocalDate startDate;

    Integer vacationDays;

    Double salary;

    @Size(max = 20)
    String employmentType;

    // 仅保留CompanyDTO字段,移除JPA注解
    private CompanyDTO employeeCompany;
}

2. 员工控制器添加跨域支持

公司控制器配置了@CrossOrigin,但员工控制器未配置,会导致前端跨域请求被浏览器拦截,添加该注解:

@CrossOrigin
@PostMapping("/employee")
public ResponseEntity<EmployeeDTO> createEmployee(@RequestBody EmployeeDTO employeeDTO){
    log.debug("Rest request to save Employee : {}",employeeDTO); // 修正日志错误:将Company改为Employee
    EmployeeDTO result = employeeService.save(employeeDTO);
    return new ResponseEntity<>(result, HttpStatus.CREATED);
}

3. 修正服务层日志错误

员工服务的save方法日志描述错误,同步修正:

@Transactional
public EmployeeDTO save(EmployeeDTO employeeDTO){
    log.debug("Request to save Employee : {}",employeeDTO);
    Employee employee = employeeMapper.toEntity(employeeDTO);
    employee = employeeRepository.save(employee);
    return employeeMapper.toDto(employee);
}

前端代码问题修正

1. 调整员工表单验证规则

EmployeeSchema中错误使用CompanySchema验证employeeCompany,但CompanySchema要求name、address、phone必填,而前端仅输入公司ID,导致验证不通过,表单无法提交。修改验证规则,仅验证公司ID:

export const EmployeeSchema = yup.object({
    name: yup.string().required("name is required"),
    surName: yup.string().required("surname is required"),
    email: yup.string().required("email is required"),
    startDate: yup.date().required("Start Date is required"),
    vacationDays: yup.number().required("Vacation days are required"),
    salary: yup.number().required("Salary is required"),
    employmentType: yup.string().required("Employment type is required"),
    // 仅验证employeeCompany的ID必填
    employeeCompany: yup.object({
        id: yup.number().required("Employee Company ID is required")
    }).required("Employee Company is required"),
});

2. 添加请求错误处理

前端fetch请求未处理错误,导致请求失败时无任何提示,添加catch块捕获异常:

const onSubmit = (data: any) => {
    if (!params?.id) {
        fetch("http://localhost:8081/api/employee", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(data),
        })
        .then((response) => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then((data) => {
            console.log(data);
            navigate(`/employee/${data?.id}`);
            toast.success("created!");
        })
        .catch((error) => {
            console.error('Error:', error);
            toast.error("Failed to create employee!");
        });
    } else {
        fetch(`http://localhost:8081/api/updateemployee/${params?.id}`, {
            method: "PUT",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(data),
        })
        .then((response) => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(() => {
            console.log("test");
            toast.info("updated!");
        })
        .catch((error) => {
            console.error('Error:', error);
            toast.error("Failed to update employee!");
        });
    }
};

3. 解决日期序列化兼容性问题

前端startDate为Date类型,JSON序列化后可能与后端LocalDate不兼容,可通过后端配置Jackson支持LocalDate序列化:
在application.properties中添加:

spring.jackson.serialization.write-dates-as-timestamps=false
spring.jackson.time-zone=UTC

内容的提问来源于stack exchange,提问作者Christophoros Feggaris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 10:08:09