Spring Boot 405 Method Not Allowed 에러 원인과 해결 방법
Spring Boot 애플리케이션에서 API 호출 시 405 Method Not Allowed 에러가 발생하는 경우가 있습니다.
이 오류는 요청한 URL은 존재하지만, 해당 URL이 요청한 HTTP 메서드를 허용하지 않을 때 발생합니다.
즉, 매핑된 컨트롤러는 있지만 GET, POST, PUT, DELETE 등의 메서드가 맞지 않는 상황입니다.
1. 405 Method Not Allowed란?
HTTP 상태 코드 405는 서버가 요청한 리소스를 알고 있지만, 해당 메서드로는 요청을 처리할 수 없음을 의미합니다.
Spring MVC에서는 HandlerMapping이 URL을 찾은 뒤, 메서드 매핑이 맞지 않으면 405를 반환합니다.
2. 원인 1: 잘못된 HTTP 메서드 사용
예를 들어, 컨트롤러가 @PostMapping만 허용하는데, GET 요청을 보내면 405가 발생합니다.
@RestController
@RequestMapping("/api")
public class SampleController {
@PostMapping("/save")
public String save() {
return "saved";
}
}
위 경우 POST /api/save는 정상 처리되지만, GET /api/save는 405가 발생합니다.
3. 원인 2: 프론트엔드와 백엔드 메서드 불일치
REST API 호출 시, 프론트엔드에서 메서드를 잘못 설정하는 경우가 많습니다.
특히 Axios, Fetch API 사용 시 method 옵션을 확인해야 합니다.
fetch("/api/save", {
method: "POST",
body: JSON.stringify({ name: "test" })
});
4. 원인 3: HiddenHttpMethodFilter 미설정 (PUT/DELETE 요청)
HTML Form은 GET과 POST만 지원하므로, PUT/DELETE를 사용하려면 HiddenHttpMethodFilter를 설정해야 합니다.
이 필터가 없으면 POST로 요청하더라도 컨트롤러의 PUT/DELETE 매핑이 호출되지 않아 405가 발생합니다.
해결 방법
@Bean
public FilterRegistrationBean<HiddenHttpMethodFilter> hiddenHttpMethodFilter(){
FilterRegistrationBean<HiddenHttpMethodFilter> filter = new FilterRegistrationBean<>(new HiddenHttpMethodFilter());
filter.setOrder(1);
return filter;
}
5. 원인 4: CORS Preflight 요청 미허용
다른 도메인에서 API를 호출할 경우, 브라우저는 OPTIONS 메서드로 Preflight 요청을 보냅니다.
이 OPTIONS 요청을 컨트롤러나 CORS 설정에서 허용하지 않으면 405가 발생할 수 있습니다.
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:3000")
.allowedMethods("GET","POST","PUT","DELETE","OPTIONS");
}
6. 원인 5: Security 설정에서 메서드 차단
Spring Security에서 HTTP 메서드를 명시적으로 제한했을 경우, 해당 메서드 요청은 405가 반환됩니다.
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(HttpMethod.POST, "/api/**").permitAll()
.anyRequest().authenticated();
}
7. 해결 체크리스트
- 컨트롤러 메서드 어노테이션(@GetMapping, @PostMapping 등) 확인
- 프론트엔드 요청 메서드(method) 옵션 확인
- PUT/DELETE 요청 시 HiddenHttpMethodFilter 등록 여부 확인
- CORS 설정에서 OPTIONS 메서드 허용 여부 확인
- Spring Security에서 HTTP 메서드 제한 여부 확인
8. 전체 예제 코드
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
@RestController
@RequestMapping("/api")
class ApiController {
@GetMapping("/hello")
public String hello() {
return "hello";
}
@PostMapping("/save")
public String save() {
return "saved";
}
}
맺음말
405 Method Not Allowed 에러는 URL이 잘못된 경우가 아니라, HTTP 메서드 불일치로 발생합니다.
컨트롤러 매핑과 프론트엔드 요청 메서드를 맞춰주는 것이 가장 기본적인 해결책입니다.
또한 PUT/DELETE, CORS, Security 설정까지 함께 점검해야 완전히 해결할 수 있습니다.
'웹개발 > Spring' 카테고리의 다른 글
| Spring Boot 500 Internal Server Error 원인 분석과 해결 방법 (2) | 2025.08.18 |
|---|---|
| Spring Boot 403 Forbidden 에러 원인과 해결 방법 총정리 (1) | 2025.08.16 |
| Spring Boot 404 Not Found 에러 발생 원인과 해결 방법 총정리 (0) | 2025.08.15 |
| Spring Boot에서 JPA와 Querydsl 함께 사용하는 방법 (설정부터 실전 예제까지) (4) | 2025.08.14 |
| Spring Boot Logback 설정 완전 정리: 로그 포맷, 파일 분리, Rolling 설정까지 (3) | 2025.08.13 |