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

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

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

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

解决方式:

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

让服务器告诉浏览器:允许跨域(返回 cross-orign-allow 响应头),就是在请求头当中,告诉浏览器这个是安全的,可以跨域:

Nginx 网关的支持

尽量不要用 add_header Acess-Control-Allow-origin *有个缺陷,cookice 可能无法处理。

# 跨域配置
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;
    }
}

# 跨域配置
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 注解

@CrossOrigin(origins = {"http://你想支持跨域的域名"}, allowCreadentials = "true")
public class UserController {

    
}

b. 添加 web全局请求拦截器

@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,参考:https://www.jianshu.com/p/b02099a435bd


补充:SpringBoot设置Cors跨域的四种方式

前言:CorsFilter / WebMvcConfigurer / @CrossOrigin 需要SpringMVC 4.2 以上的版本才支持,对应SpringBoot 1.3 版本以上都支持这些CORS特性。不过,使用SpringMVC4.2 以下版本的小伙伴也不用慌,直接使用方式4通过手工添加响应头来授权CORS跨域访问也是可以的。

链接:https://www.jianshu.com/p/b02099a435bd

首先一点:跨域问题,后端解决,有如下四种方式。

方式1:返回新的CorsFilter

@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

@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)

@Controller
@RequestMapping("/admin/sysLog")
@CrossOrigin
public class SysLogController {
 
}

方式4:手工设置响应头(HttpServletResponse )

这种方式,可以自己手工加到,具体的controller,inteceptor,filter等逻辑里。

@RequestMapping("/test")
@ResponseBody
public String test(){
response.addHeader("Access-Control-Allow-Origin", "http://localhost:8080");
return "success";
}

总结:以上是设置cors跨域后端解决的四种方式,本质都是类似最后一种设置响应头,不过都是各自包实现了不同的封装逻辑。

最后:

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

在这里插入图片描述

此插件为插件,打开后可访问接口,旧版浏览器可直接拖到扩展程序中安装,新版浏览器需要将扩展名修改成rar并解压,然后点击“加载已解压的扩展程序”安装。 ======================插件概述谷歌译文====================== 轻松将(Access-Control-Allow-Origin:*)规则添加到响应标头。 允许CORS:通过Access-Control-Allow-Origin,您可以轻松地在Web应用程序中执行Ajax请求。 只需激活插件并执行请求。默认情况下(在JavaScript API中),CORS源资源共享在现代浏览器中被阻止。安装此加载项将使您可以解除阻止此功能。请注意,将插件添加到浏览器后,默认情况下它处于非活动状态(工具栏图标为灰色C字母)。如果要激活加载项,请按一次工具栏图标。图标将变为橙色的C字母。 ======================插件概述谷歌译文====================== ========================插件概述原文======================== Easily add (Access-Control-Allow-Origin: *) rule to the response header. Allow CORS: Access-Control-Allow-Origin lets you easily perform cross-domain Ajax requests in web applications. Simply activate the add-on and perform the request. CORS or Cross Origin Resource Sharing is blocked in modern browsers by default (in JavaScript APIs). Installing this add-on will allow you to unblock this feature. Please note that, when the add-on is added to your browser, it is in-active by default (toolbar icon is grey C letter). If you want to activate the add-on, please press on the toolbar icon once. The icon will turn to orange C letter. ========================插件概述原文========================
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值