一、简介

Web 开发经常会遇到跨域问题,解决方案有:jsonp,iframe,CORS 等等

1.1、CORS与JSONP相比

1、JSONP只能实现GET请求,而CORS支持所有类型的HTTP请求。

2、使用CORS,开发者可以使用普通的XMLHttpRequest发起请求和获得数据,比起JSONP 有更好的错误处理。

3、JSONP主要被老的浏览器支持,它们往往不支持CORS,而绝大多数现代浏览器都已经支持了CORS浏览器支持情况

Chrome 3+

Firefox 3.5+

Opera 12+

Safari 4+

Internet Explorer 8+

二、实现CORS

说明:在springMVC中可以配置全局的规则,也可以使用@CrossOrigin注解进行细粒度的配置

2.1、全局配置

方式一:注册bean

packagecom.example.demo.utils.configuration;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.web.servlet.config.annotation.CorsRegistry;importorg.springframework.web.servlet.config.annotation.WebMvcConfigurer;importorg.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;/***CreatedbyDELLon2017/6/18.*/@ConfigurationpublicclassCustomCorsConfiguration{@BeanpublicWebMvcConfigurercorsConfigurer(){returnnewWebMvcConfigurerAdapter(){@OverridepublicvoidaddCorsMappings(CorsRegistryregistry){registry.addMapping("/api/**").allowedOrigins("http://localhost:8080");}};}}

说明:表示对于/api请求下的所以资源,允许http://localhost:8080访问

方式二:继承WebMvcConfigurerAdapter

packagecom.example.demo.utils.configuration;importorg.springframework.web.servlet.config.annotation.CorsRegistry;importorg.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;/***跨域请求处理*@Author:我爱大金子*@Description:跨域请求处理*@Date:Createdin10:122017/6/18*/@ConfigurationpublicclassCustomCorsConfiguration2extendsWebMvcConfigurerAdapter{@OverridepublicvoidaddCorsMappings(CorsRegistryregistry){registry.addMapping("/api/**").allowedOrigins("http://localhost:8080");}}

说明:表示对于/api请求下的所以资源,允许http://localhost:8080访问


2.2、细粒度配置

在controller中加入@CrossOrigin注解,如:@CrossOrigin(origins = "http://localhost:8080")