Search code examples
javaspring-boothttp-status-code-404put

Backend Spring-Boot and FE React - 404 error for PUT:/update whereas other CRUD operations are working


I'm working on a Spring Boot application with a React frontend. I have an endpoint /employees/update that's supposed to update an employee record when a PUT request is made. However, I'm getting a 404 error when I try to access this endpoint.

Here's the relevant code:

// 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() 
}

When I start the application and make a PUT request to http://localhost:5173/employees/update with a valid id and Employee object, I expect the employee to be updated and the updated employee to be returned. However, I get a 404 error instead. Error updating employee AxiosError

Interestingly, other endpoints like http://localhost:5173/employees/delete and http://localhost:5173/employees/save are working fine.

Here's the project link for reference: [https://github.com/harihargithub/EmpMgmtSys].

Backend: mpMgmtSys_sboot_vite_react_mysql_sf> mvn install clean then mvn spring-boot:run (Port:8080)

Frontend: EmpMgmtSys_sboot_vite_react_mysql_sf\empvitereact>npm install then run dev (Port:5173)

@ empvitereact/src/main.jsx - // .env - VITE_SYNCFUSION_LICENSE_KEY='Your SF Licence Key' registerLicense(import.meta.env.VITE_SYNCFUSION_LICENSE_KEY); or you may include your license directly here.

Does anyone know why I might be getting a 404 error for the /employees/update endpoint?



Solution

  • Success!

    Changes made to /update @ EmployeeController.java, EmployeeService.java, EmployeeList.jsx and vite.config.js and now all CRUD operations including update are working fine after repeated trail & error.

    Push to harihargithub/EmpMgmtSys done.

    Thanks & Regards