inblog logo
|
codingb
    Spring

    CORS 실습 (+CORS Policy)

    coding S's avatar
    coding S
    Mar 20, 2024
    CORS 실습 (+CORS Policy)

    [ /test ]

    notion image
    notion image
    💡
    @ResponseBody 붙여야 나온다고 함!
     

    [ /test/page ]

    notion image

    [ page.mustache ]

    notion image
    <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <h1>page</h1> <hr> <script> async function download() { let response = await fetch("http://localhost:8080/test"); let body = await response.text(); console.log(body); } download(); </script> </body> </html>
    💡
    fetch -> 자바 스크립트로 통신 요청
     

    [ test/page로 이동하자 ]

    test/page로 이동하면 자바 스크립트가 실행되고, 내부적으로 ajax가 돈다. 이제 console.log에 보면...
    notion image
    💡
    ok가 나왔다! 같은 도메인이라 js를 허용해준 것!
     

    [ 다른 도메인이라면? ] → vs코드에 코드를 옮겨서 실행해보자

    notion image
    notion image
    💡
    거부당했다!!!
     

    [ CORS Policy ] 꼭 무슨 말인지 살펴봐야 할 오류 → 번역기라도 돌려!!

    notion image
    Access to fetch at 'http://localhost:8080/test' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
    💡
    이게 바로 CORS Policy로 인해 발생한 오류. 서로 다른 origin 에서 자바 스크립트 요청이 들어와서 차단해버림.

    [ 해결법 ]

    서버에서 [ Acess-Control-Allow-Origin ] 이라고, 이 origin에 허용해주는 설정이 헤더에 필요하다 이 오류를 해결할 수 있는건 서버! (자원의 소유자가 서버라서. 소유권(갑) 서버) 서버가 크로스 도메인들(다른 도메인들)을 허용해줘야 해결이 됨!! -> 서버가 결정하는 것!!!
     

     
    💡
    ip랑 port 둘 다 같아야지 도메인이 같다고 함!! (정확히는… 도메인이 아니라 origin…)
     
    Share article

    codingb

    RSS·Powered by Inblog