반응형

@CrossOrigin 어노테이션을 사용하여 CORS 설정을 할 수 있다.

 

 

특정 컨트롤러에 대해 CORS를 허용하려면 다음과 같이 설정하면 된다.

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {
  
  @CrossOrigin(origins = "http://localhost:3000")  // Vite 서버 주소
  @GetMapping("/myEndpoint")
  public String myEndpoint() {
    return "Hello, World!";
  }
}

 

 

전역 CORS 설정을 하려면 WebMvcConfigurer를 구현해야 한다.

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:3000")  // Vite 서버 주소
                .allowedMethods("GET", "POST", "PUT", "DELETE");
    }
}
반응형

'Basic > Java' 카테고리의 다른 글

Java 정렬된 arraylist 만들기 - TreeSet  (0) 2024.01.29
@ApiIgnore 어노테이션이란  (0) 2023.06.15
IoC (Inversion of Control)란?  (0) 2023.06.13
EJB(Enterprise JavaBeans)란?  (0) 2023.06.12
[Spring] ClassPathResource와 classpath* 차이  (0) 2023.05.06