后端 Spring-Boot 和 FE React - PUT:/update 出现 404 错误,而其他 CRUD 操作正在运行

问题描述 投票:0回答:1

我正在开发一个带有 React 前端的 Spring Boot 应用程序。我有一个端点

/employees/update
,它应该在发出
PUT
请求时更新员工记录。但是,当我尝试访问此端点时收到 404 错误。

相关代码如下:

// Employee.java
@Entity
@Table(name = "employees")
@Getter
@Setter
@NoArgsConstructor
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String firstName;
    private String lastName;
    private String email;

}
@Repository
public interface EmployeeJpaRepository extends JpaRepository<Employee, Long> {

}
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeJpaRepository employeeJpaRepository;

    @Override
    public Employee updateEmployeeById(long employeeId, Employee updatedEmployee) {
        Employee existingEmployee = this.findEmployeeById(employeeId);
        existingEmployee.setFirstName(updatedEmployee.getFirstName());
        existingEmployee.setLastName(updatedEmployee.getLastName());
        existingEmployee.setEmail(updatedEmployee.getEmail());
        return this.employeeJpaRepository.save(existingEmployee);
    }
// EmployeeController.java
    package com.abj.EmpMgmtSys.controller;

import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
// import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
//import org.springframework.web.server.ResponseStatusException;

import com.abj.EmpMgmtSys.model.Employee;
import com.abj.EmpMgmtSys.service.EmployeeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@CrossOrigin(origins = "http://localhost:5173")
@RestController
@RequestMapping("/employees")
public class EmployeeController {

    private static final Logger logger = LoggerFactory.getLogger(EmployeeController.class);

    @Autowired
    private EmployeeService employeeService;

    @GetMapping("/list")
    public ResponseEntity<?> listEmployees() {
        Set<Employee> employees = this.employeeService.fetchAll();
        logger.info("Fetched employees: {}", employees); // Log the fetched employees
        return ResponseEntity.ok(employees);
    }

    @PostMapping("/save")
    public Employee saveEmployee(@RequestBody Employee employee) {
        return this.employeeService.saveEmployee(employee);
    }

    @PutMapping("/update")
    public Employee updateEmployee(@RequestParam("id") long employeeId, @RequestBody Employee updatedEmployee) {
        logger.info("Received update request for employee with ID: {}", employeeId);

        return employeeService.updateEmployeeById(employeeId, updatedEmployee);
    }

    @PostMapping("/delete")
    public void deleteEmployeeById(@RequestParam("id") long employeeId) {
        this.employeeService.deleteEmployeeById(employeeId);
    }

    @GetMapping("/search")
    public Set<Employee> searchEmployees(@RequestParam("keyword") String keyword) {
        return employeeService.searchEmployees(keyword);
    }

    @GetMapping("/list-sorted/{sortOrder}")
    public List<Employee> listEmployeesSorted(@PathVariable String sortOrder) {
        if ("desc".equals(sortOrder)) {
            return employeeService.getAllEmployeesSortedByFirstNameDesc();
        } else {
            return employeeService.getAllEmployeesSortedByFirstName();
        }
    }
}
@Configuration
public class AppConfig {

    @Autowired
    private UserDetailsService userDetailsService;

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        final CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:5173")); // Allow frontend origin
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
        configuration.setAllowCredentials(true);
        // ...
    }

    // ...
    .antMatchers("/login", "/loginPage*").permitAll() 
    .antMatchers("/employees/list").permitAll()
    .antMatchers(HttpMethod.POST, "/employees/save").permitAll()
    .antMatchers(HttpMethod.PUT, "/employees/update").permitAll()
    .antMatchers("/employees/delete").permitAll() 
}

当我启动应用程序并使用有效的

PUT
http://localhost:5173/employees/update
对象向
id
发出
Employee
请求时,我希望更新员工并返回更新后的员工。但是,我收到了 404 错误。更新员工 AxiosError 时出错

有趣的是,其他端点(如

http://localhost:5173/employees/delete
http://localhost:5173/employees/save
)工作正常。

以下是项目链接供参考:[https://github.com/harihargithub/EmpMgmtSys]。

后端:mpMgmtSys_sboot_vite_react_mysql_sf> mvn install clean 然后 mvn spring-boot:run (端口:8080)

前端:EmpMgmtSys_sboot_vite_react_mysql_sf mpvitereact>npm install然后运行dev(端口:5173)

@ empvitereact/src/main.jsx - // .env - VITE_SYNCFUSION_LICENSE_KEY='您的 SF 许可证密钥' registerLicense(import.meta.env.VITE_SYNCFUSION_LICENSE_KEY);或者您可以直接在此处添加您的许可证。

有谁知道为什么我可能会收到

/employees/update
端点的 404 错误?


java spring-boot http-status-code-404 put
1个回答
0
投票

成功!

对 /update @ EmployeeController.java、EmployeeService.java、EmployeeList.jsx 和 vite.config.js 进行的更改,现在所有 CRUD 操作(包括更新)在反复尝试和错误后都工作正常。

推送到 harihargithub/EmpMgmtSys 已完成。

感谢与问候

© www.soinside.com 2019 - 2024. All rights reserved.