跨域问题(Allow CORS)解决(3 种方法)

跨域问题(Allow CORS)解决(3 种方法)

@[toc]

跨域问题:浏览器为了用户的安全,仅允许向同域,同端口的服务器发送请求。

浏览器在发送请求的时候,会发送一个预检请求(一般请求方法是: options)。作用:提前探探路,是否符合同域策略什么的

解决方式:

  1. 把域名,端口改为相同
  2. 网关支持

让服务器告诉浏览器:允许跨域(返回 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;
    }
}
  1. 修改后端服务
    1. 配置 @ 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跨域后端解决的四种方式,本质都是类似最后一种设置响应头,不过都是各自包实现了不同的封装逻辑。

最后:

"在这个最后的篇章中,我要表达我对每一位读者的感激之情。你们的关注和回复是我创作的动力源泉,我从你们身上吸取了无尽的灵感与勇气。我会将你们的鼓励留在心底,继续在其他的领域奋斗。感谢你们,我们总会在某个时刻再次相遇。"

相关推荐
Java技术小馆4 分钟前
GitDiagram如何让你的GitHub项目可视化
java·后端·面试
Codebee21 分钟前
“自举开发“范式:OneCode如何用低代码重构自身工具链
java·人工智能·架构
星星电灯猴28 分钟前
iOS 性能调试全流程:从 Demo 到产品化的小团队实战经验
后端
程序无bug36 分钟前
手写Spring框架
java·后端
程序无bug38 分钟前
Spring 面向切面编程AOP 详细讲解
java·前端
JohnYan38 分钟前
模板+数据的文档生成技术方案设计和实现
javascript·后端·架构
全干engineer1 小时前
Spring Boot 实现主表+明细表 Excel 导出(EasyPOI 实战)
java·spring boot·后端·excel·easypoi·excel导出
Da_秀1 小时前
软件工程中耦合度
开发语言·后端·架构·软件工程
Fireworkitte1 小时前
Java 中导出包含多个 Sheet 的 Excel 文件
java·开发语言·excel
GodKeyNet1 小时前
设计模式-责任链模式
java·设计模式·责任链模式