[SpringBoot] CORS ์ฒ˜๋ฆฌํ•˜๊ธฐ

    ๋ฐ˜์‘ํ˜•

    2022.07.06 - 2์ฐจ์ ์œผ๋กœ ์ถ”๊ฐ€๋œ ๋‚ด์šฉ์ด ์žˆ์Šต๋‹ˆ๋‹ค.

    https://lucete-stellae.tistory.com/98

     

    SpringBoot 2.7+ CORS ์ด์Šˆ ๋ฐ ํ•ด๊ฒฐ๋ฐฉ๋ฒ•

    ๊ฐ„๋‹จํ•˜๊ฒŒ ๋งŒ๋“  API ์„œ๋ฒ„๋ฅผ ํ…Œ์ŠคํŠธ ํ•˜๊ธฐ ์œ„ํ•ด ๋กœ์ปฌ์—์„œ ๋Œ๋ฆฌ๋˜ ๋„์ค‘ ํ•ด๋‹น ์ด์Šˆ๋ฅผ ๋งŒ๋‚ฌ๋‹ค. ๊ตฌ์„ฑ์€ ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค. localhost:8080/users - SpringBoot API Server ์—์„œ ์œ ์ € ๋ฐ์ดํ„ฐ๋ฅผ ๋ฆฌํ„ด. localhost:8090/index.html..

    lucete-stellae.tistory.com

     

    1. Global WebConfig

    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("/**") // CORS๋ฅผ ์ ์šฉํ•  URL ํŒจํ„ด.
                    /*
                     * [addMapping ์„ค์ •๋งŒ ํ–ˆ์„ ๋•Œ์˜ ๊ธฐ๋ณธ ๊ฐ’]
                     * Allow all origins.
                     * Allow "simple" methods GET, HEAD and POST.
                     * Allow all headers.
                     * Set max age to 1800 seconds (30 minutes).
                     */
                    .allowedOrigins("*") // CORS๋ฅผ ํ—ˆ์šฉํ•  Origin ์ง€์ •. ํŠน์ • ์ฃผ์†Œ์—์„œ ์š”์ฒญ ์‹œ ํ—ˆ์šฉํ•˜๋Š” ๊ฒƒ์„ ์˜๋ฏธ. .allowedOrigins("http://localhost:8080","http://localhost:80") ์™€ ๊ฐ™์ด ์ง์ ‘ ์ฃผ์†Œ ๋งคํ•‘๊ฐ€๋Šฅ.
                    .allowedMethods("GET", "POST") // CORS๋ฅผ ํ—ˆ์šฉํ•  ๋ฉ”์†Œ๋“œ.
                    .maxAge(3000); // ์š”์ฒญ์— ๋Œ€ํ•œ ์บ์‹ฑ ์ฒ˜๋ฆฌ ์‹œ๊ฐ„
        }
    }

     

    2. Annotation 

    ๋™์ผํ•œ ๋ฐฉ์‹์œผ๋กœ ์ปจํŠธ๋กค๋Ÿฌ ์ „์ฒด ํ˜น์€ ๋ฉ”์†Œ๋“œ์— ์ ์šฉ ๊ฐ€๋Šฅ.

    @RequestMapping("/")
    @CrossOrigin(origins = "*", allowedHeaders = "*") 
    public class SampleController {
    
        @RequestMapping("/getData", method = RequestMethod.POST)
        @CrossOrigin(origins = "*", allowedHeaders = "*")
        public int SampleGetData() {
        	...
        }
    }

     

    ์ฐธ๊ณ  ๊ฐ€์ด๋“œ

    https://spring.io/guides/gs/rest-service-cors/

     

    Enabling Cross Origin Requests for a RESTful Web Service

    this guide is designed to get you productive as quickly as possible and using the latest Spring project releases and techniques as recommended by the Spring team

    spring.io

     

    728x90
    ๋ฐ˜์‘ํ˜•

    ๋Œ“๊ธ€