跨域问题(Allow CORS)解决(3 种方法)
@[toc]
跨域问题:浏览器为了用户的安全,仅允许向同域,同端口的服务器发送请求。
浏览器在发送请求的时候,会发送一个预检请求(一般请求方法是: options)。作用:提前探探路,是否符合同域策略什么的
解决方式:
- 把域名,端口改为相同
- 网关支持
让服务器告诉浏览器:允许跨域(返回 cross-orign-allow 响应头),就是在请求头当中,告诉浏览器这个是安全的,可以跨域:
Nginx 网关的支持
尽量不要用 add_header Acess-Control-Allow-origin *
有个缺陷,cookice 可能无法处理。
json
# 跨域配置
location ^~ /api/ {
proxy_pass http://127.0.0.1:8080/api/; # 配置反向代理
add_header 'Access-Control-Allow-Origin' $http_origin; # 允许任何跨域
add_header 'Access-Control-Allow-Credentials' 'true'; # 允许后端带上 cookie
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers '*';
if ($request_method = 'OPTIONS') { # options 预检请求通过了,就可以访问了。
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Origin' $http_origin;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
}
nginx
# 跨域配置
location ^~ /api/ {
proxy_pass http://127.0.0.1:8080/api/; # 配置反向代理
add_header 'Access-Control-Allow-Origin' $http_origin; # 允许任何跨域
add_header 'Access-Control-Allow-Credentials' 'true'; # 允许后端带上 cookie
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers '*';
if ($request_method = 'OPTIONS') { # options 预检请求通过了,就可以访问了。
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Origin' $http_origin;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
}
- 修改后端服务
- 配置
@ CrossOrigin
注解
- 配置
java
@CrossOrigin(origins = {"http://你想支持跨域的域名"}, allowCreadentials = "true")
public class UserController {
}
b. 添加 web
全局请求拦截器
java
@Configuration
public class WebMvcConfg implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
//设置允许跨域的路径
registry.addMapping("/**")
//设置允许跨域请求的域名
//当 **Credentials为true时,** Origin不能为星号,需为具体的ip地址【如果接口不带cookie,ip无需设成具体ip】
.allowedOrigins("http://localhost:9527", "http://127.0.0.1:9527", "http://127.0.0.1:8082", "http://127.0.0.1:8083")
//是否允许证书 不再默认开启
.allowCredentials(true)
//设置允许的方法
.allowedMethods("*")
//跨域允许时间
.maxAge(3600);
}
}
c. 定义新的 corsFilter Bean,参考:www.jianshu.com/p/b02099a43...
补充:SpringBoot设置Cors跨域的四种方式
前言:CorsFilter / WebMvcConfigurer / @CrossOrigin 需要SpringMVC 4.2 以上的版本才支持,对应SpringBoot 1.3 版本以上都支持这些CORS特性。不过,使用SpringMVC4.2 以下版本的小伙伴也不用慌,直接使用方式4通过手工添加响应头来授权CORS跨域访问也是可以的。
链接:www.jianshu.com/p/b02099a43...
首先一点:跨域问题,后端解决,有如下四种方式。
方式1:返回新的CorsFilter
java
@Configuration
public class CorsConfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.setMaxAge(3600L);
corsConfiguration.setAllowCredentials(true);
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
}
方式2:重写WebMvcConfigurer
java
@Configuration
public class WebMvcConfg implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
//设置允许跨域的路径
registry.addMapping("/**")
//设置允许跨域请求的域名
//当**Credentials为true时,**Origin不能为星号,需为具体的ip地址【如果接口不带cookie,ip无需设成具体ip】
.allowedOrigins("http://localhost:9527", "http://127.0.0.1:9527", "http://127.0.0.1:8082", "http://127.0.0.1:8083")
//是否允许证书 不再默认开启
.allowCredentials(true)
//设置允许的方法
.allowedMethods("*")
//跨域允许时间
.maxAge(3600);
}
}
方式3:使用注解(@CrossOrigin)
kotlin
@Controller
@RequestMapping("/admin/sysLog")
@CrossOrigin
public class SysLogController {
}
方式4:手工设置响应头(HttpServletResponse )
这种方式,可以自己手工加到,具体的controller,inteceptor,filter等逻辑里。
kotlin
@RequestMapping("/test")
@ResponseBody
public String test(){
response.addHeader("Access-Control-Allow-Origin", "http://localhost:8080");
return "success";
}
总结:以上是设置cors跨域后端解决的四种方式,本质都是类似最后一种设置响应头,不过都是各自包实现了不同的封装逻辑。
最后:
"在这个最后的篇章中,我要表达我对每一位读者的感激之情。你们的关注和回复是我创作的动力源泉,我从你们身上吸取了无尽的灵感与勇气。我会将你们的鼓励留在心底,继续在其他的领域奋斗。感谢你们,我们总会在某个时刻再次相遇。"