ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Spring] ์ „์ž์ •๋ถ€ํ”„๋ ˆ์ž„์›Œํฌ์—์„œ CORS ๋ฌธ์ œ ํ•ด๊ฒฐํ•˜๊ธฐ
    DEV ๐Ÿ’™/JAVA Spring 2021. 8. 11. 12:59
    ๋ฐ˜์‘ํ˜•


    ์ „์ž์ •๋ถ€ํ”„๋ ˆ์ž„์›Œํฌ ๊ฐœ๋ฐœ ์ค‘ ์™ธ๋ถ€ API๋ฅผ ์‚ฌ์šฉํ•˜๋‹ค๊ฐ€

    [ Access to XMLHttpRequest at 'A' from origin 'B' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. ]

    CORS Error ๋•๋ถ„์— ๊ณจ๋จธ๋ฆฌ๋ฅผ ์•“์•˜๋‹ค..ใ…Žใ…Ž
    ์™ธ๋ถ€ api ๋ฅผ ์‚ฌ์šฉํ• ๋ ค๋‹ค๋ณด๋‹ˆ CORS ํ‘œ์ค€์—์„œ ๋ฒ—์–ด๋‚˜์„œ ์ƒ๊ธฐ๋Š” ์—๋Ÿฌ์ด๋‹ค

    ๊ตฌ๊ธ€๋ง์œผ๋กœ ์ฐพ์•„๋ณธ ํ•ด๊ฒฐ ๋ฐฉ๋ฒ•์œผ๋กœ๋Š”

    1 ์„œ๋ฒ„๋‹จ์—์„œ ์™ธ๋ถ€url ํ—ˆ์šฉ ์„ค์ •ํ•˜๋Š” ๋ฐฉ๋ฒ•
    2 ๋ฏธ๋“ค์›จ์–ด๋ฅผ ํ™œ์š”ํ•˜๋Š” ๋ฐฉ๋ฒ•
    3 ํ”„๋ก์‹œ ์„œ๋ฒ„๋ฅผ ์šฐํšŒํ•˜๋Š” ๋ฐฉ๋ฒ•
    4 ํฌ๋กฌ์˜ ํ™•์žฅํ”„๋กœ๊ทธ๋žจ์„ ํ™œ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•

    ๊ฐœ๋ฐœ ๋ฐ ํ…Œ์ŠคํŠธ ์‹œ์—๋Š” 4๋ฒˆ ๋ฐฉ๋ฒ• ํ™•์žฅ ํ”„๋กœ๊ทธ๋žจ์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ๊ฐ€์žฅ ๊ฐ„๋‹จํ•œ ๋ฐฉ๋ฒ•์ด์—ˆ๋‹ค
    ๋‚ด๊ฐ€ ์„ค์น˜ํ•œ ๊ฒƒ์€ 'Muyor'์ด ์ œ๊ณตํ•˜๋Š” 'Allow CORS: Access-Control-Allow-Origin'



    ๊ทผ๋ฐ ์ด์ œ... ๋ฐฐํฌํ•˜๋Š” ์›น์˜ ๊ฒฝ์šฐ๋Š” ์‚ฌ์šฉ์ž๋“ค์—๊ฒŒ '๋ชจ๋‘ ์ด ํ”Œ๋Ÿฌ๊ทธ์ธ ์„ค์น˜ํ•˜์„ธ์š”๐Ÿ˜€' ํ•  ์ˆ˜๋Š” ์—†์œผ๋‹ˆ๊นŒ

     


    ์Šคํ”„๋ง์—์„œ ๊ฐ„๋‹จํ•˜๊ฒŒ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋Š” ๋ฐฉ๋ฒ•์ด ์žˆ์—ˆ๋‹ค

    โœ… ์ฒซ๋ฒˆ์งธ๋Š” WebConfig์— CORS๋ฅผ ์„ค์ •ํ•ด์ฃผ๋Š” ๋ฐฉ๋ฒ•!

    @Configuration
    public class WebConfig implements WebMvcConfigurer {
    
    	@Override
        public void addCorsMappings(CorsRegistry reg) {
        	reg.addMapping("/**").allowedOrigins("URL");
        }
        
    }


    ์ด๋ ‡๊ฒŒ ํ•˜๋ฉด CORS ๊ด€๋ จํ•ด์„œ ์„ค์ •ํ•  ์ˆ˜ ์žˆ๋‹ค
    allowedOrigins("URL"); ์„ค์ •์œผ๋กœ ํ•ด๋‹น URL์—์„œ ์˜ค๋Š” ์š”์ฒญ์€ ๋‹ค๋ฅธ Origin์ด๋ผ๋„ ํ—ˆ์šฉํ•ด! ํ•˜๊ณ  ์•Œ๋ ค์ฃผ๋Š” ๊ฒƒ!

     

    โœ… ๋‘๋ฒˆ์งธ ๋ฐฉ๋ฒ•์€ ํ”„๋ก์‹œ๋ฅผ ๋งŒ๋“ค์–ด์ฃผ๋Š” ๊ฒƒ

    @Controller
    public class CorsMapper {
    
    	@RequestMapping(value="/proxy.do")
        @ResponseBody
        public String proxy() throws Exception {
        
        	String url = "์ ‘๊ทผ์„ ํ—ˆ์šฉํ•  URL";
            RestTemplate restTemplate = new RestTemplate();
            
            return restTemplate.getForObject(url, String.class);
        }
    }

    RestTemplate์„ ์ด์šฉํ•ด์„œ ์„œ๋ฒ„์— ์š”์ฒญ์„ ๋ณด๋‚ด๊ณ  ์‘๋‹ต์„ ๋ฆฌํ„ดํ•œ๋‹ค

    ์ด ๋ฉ”์†Œ๋“œ๋ฅผ ํ”„๋ก ํŠธ๋‹จ์—์„œ

    <script type="text/javascript">
    
    	...
        
    	var url = "/proxy.do";
    	var features = parser.read(vw.GMLParserType.GEOJSON, url, "EPSG:4326");
    	
        ...
        
    </script>

    ์ด๋Ÿฐ ์‹์œผ๋กœ ๋ถˆ๋Ÿฌ์„œ ์‚ฌ์šฉํ•˜๋ฉด ํ•ด๊ฒฐ!

    ๋‚˜์ฒ˜๋Ÿผ ์„œ๋ฒ„ ์…‹ํŒ…์„ ์†๋Œˆ ์ˆ˜ ์žˆ๋Š” ์ƒํ™ฉ์ด ์•„๋‹ˆ๋ผ๋ฉด
    ์œ„ ๋‘๊ฐ€์ง€ ๋ฐฉ๋ฒ•์ด ๊ฐ€์žฅ ๊ฐ„๋‹จํ•œ ํ•ด๊ฒฐ์ฑ…์ธ๋“ฏํ•˜๋‹ค๐Ÿ˜

    ๋ฐ˜์‘ํ˜•
Designed by Tistory.