배경
우리가 지금하고있는 많은 프로젝트는 전면과 후면 끝에서 분리되어 매우 일반적인 문제로 이어집니다. 당사 페이지와 인터페이스는 다른 도메인 이름 아래에 있습니다. Ajax를 통해 백엔드 인터페이스에 액세스하면 크로스 도메인 문제가 발생합니다. 이 문제를 어떻게 해결할 수 있습니까? 일반적으로 CORS와 JSONP의 두 가지 솔루션이 있습니다. Spring은 CORS의 구성을 단순화하고 제공하는 CORS를 살펴 보겠습니다.
크로스 도메인 문제 설명
웹 개발은 종종 크로스 도메인 문제에 직면하며 솔루션은 JSONP, IFRAME, CORS 등을 포함합니다.
JSONP와 비교 한 CORS :
1. JSONP는 GET 요청 만 구현할 수 있지만 CORS는 모든 유형의 HTTP 요청을 지원합니다.
2. CORS를 사용하여 개발자는 일반 XMLHTTPREQUEST를 사용하여 요청을 시작하고 데이터를 얻을 수 있으며, 이는 JSONP보다 오류 처리가 더 좋습니다.
3. JSONP는 주로 오래된 브라우저에서 지원됩니다. 그들은 종종 CORS를 지원하지 않으며 대부분의 현대식 브라우저는 이미 CORS를 지원합니다.
webmvcconfigurer 객체
CORS 매핑을 구성하기 위해 WebMVCConfigurer 객체를 초기화 할 수 있습니다.
@ConfigurationPublic Class CorsCongiguration {@bean public webmvcconfigurer corsconfigurer () {return new new webmvcconfigureradapter () {@override public void addcorsmappings (corsregistry registry) {registry.addmapping ( "/api/**"); // enlainorigins ( "http://domain2.com") // 소스 도메인 이름을 지정 // "put", "delete") // .allowedHeaders ( "header1", "header2", "header3") // .ExpiteHer ( "header1", ""3600). }}; }}WebMvcConfigurerAdapter를 상속합니다
이 방법은 위의 방법과 매우 유사합니다
@configuration @enablewebmvcpublic class corsconfiguration_2 확장 webmvcconfigureradapter {@override public void addcorsmappings (corsregistry registry) {registry.addmapping ( "/api/**"); }}Corsfilter
이 방법은 지금 거의 사용되지 않습니다
@component@enablewebmvcpublic class corsfiltercongiguration 확장 corsfilter {public corsfiltercongiguration (corsconfigurationsource configsource) {super (configsource); } @bean public filterregistrationbean corsfilter () {urlbasedCorsConfigUrationSource 소스 = new urlBasedCorsConfigUrationSource (); CorsConfiguration config = new CorsConfiguration (); config.setallowcredentials (true); config.addallowedorigin ( "*"); // config.addallowedorigin ( "http://domain1.com"); config.addallowedHeader ( "*"); config.addallowedMethod ( "*"); source.registercorsconfiguration ( "/api/**", config); FilterRegistrationBean Bean = New FilterRegistrationBean (New Corsfilter (Source)); bean.setorder (0); // 모든 필터 전에 콩을 반환해야합니다. }}위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.