1、spring 解决跨域方案1 JSONP
参考该文档: http://hpgary.iteye.com/blog/2389640
2、spring 解决跨域方案2
服务器端resetful接口类或者方法上加注解 @CrossOrigin,一键轻松实现跨域,类写法如下:
@RestController
@CrossOrigin
public class TestController {
@RequestMapping("/get1")
public ResultBean get1(){
return new ResultBean("get ok1");
}
}
js写法如下,当然js代码和resetful接口不在同一个端口下:
$.post("http://127.0.0.1:8080/get1" , {} , function(result){alert( result.msg );},"json")
3、nginx 轻松实现跨域 1
java代码设置下来响应header也可以实现跨域功能
server{
listen 80;
server_name www.gary.com;
location /{
proxy_pass http://127.0.0.1:8080/ ;
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Max-Age 3600;
add_header Access-Control-Allow-Credentials true ;
add_header Access-Control-Allow-Origin $http_origin;
add_header Access-Control-Allow-Headers $http_Access_control_allow_headers ;
if ($request_method = OPTIONS){
return 200 ;
}
}
}
4、nginx 轻松实现跨域 2
这里浏览器访问的是nginx不是真实server
server{
listen 80;
server_name www.gary.com;
location /{
proxy_pass http://127.0.0.1:81/ ;
}
location /ajax{
proxy_pass http://127.0.0.1:8080/ ;
}
}
js写法如下,当然js代码和resetful接口不在同一个端口下:
$.post("/ajax/get1" , {} , function(result){alert( result.msg );},"json");
5、spring cloud zuul实现跨域方式
实现原理参考第三种:
@Bean
public CorsFilter corsFilter(){
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials( true );
config.setAllowedOrigins( Arrays.asList("*"));
config.setAllowedHeaders( Arrays.asList( "*" ));
config.setAllowedMethods( Arrays.asList("*"));
config.setMaxAge( 1800L ) ;
source.registerCorsConfiguration("/**", config);
return new CorsFilter( source );
}