首页 前端知识 springboot如何解决跨域问题(4种方式)

springboot如何解决跨域问题(4种方式)

2024-02-26 20:02:18 前端知识 前端哥 511 815 我要收藏

目录

@CrossOrigin 

WebMvcConfigurer 

Filter

Nginx


@CrossOrigin 

方法上加@CrossOrigin注解即可

查看源码就显而易见了 

 但是在多模块 多控制器 多个方法下 会显得代码冗余 不推荐用它到项目的每一个地方

WebMvcConfigurer 

实现WebMvcConfigurer接口 重写addCorsMappings()方法即可

@Configuration
public class CORSWebMvcConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
//添加映射路径
registry.addMapping("/**")
//是否发送Cookie
.allowCredentials(true)
//设置放行哪些原始域 SpringBoot2.4.4下低版本使用.allowedOrigins("*")
.allowedOriginPatterns("*")
//放行哪些请求方式
.allowedMethods(new String[]{"GET", "POST", "PUT", "DELETE"})
//.allowedMethods("*") //或者放行全部
//放行哪些原始请求头部信息
.allowedHeaders("*")
//暴露哪些原始请求头部信息
.exposedHeaders("*");
}
复制

注意springboot的版本(2.2.4以下使用alloweOrigins() 以上使用allowedOrginPatterns())

Filter

不需要注册,直接使用springboot提供的 CrosFilter

import org.springframework.web.filter.CorsFilter;
复制
@Configuration
public class CORSWebFilter {
@Bean
public CorsFilter corsFilter(){
CorsConfiguration config = new CorsConfiguration();
// 允许跨域的头部信息
config.addAllowedHeader("*");
// 允许跨域的方法
config.addAllowedMethod("*");
// 可访问的外部域
config.addAllowedOrigin("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
CorsFilter corsFilter = new CorsFilter(source);
return corsFilter;
}
复制

Nginx

指令

nginx.exe 启动nginx

nginx.exe -s stop 停止nginx

ngin -s reload 重启nginx

netstat -ano | findstr 80 产看是否被占用了

taskkill -pid xxx   如果是的就kill掉

在  location / {} 里面直接添加这段代码即可

add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
if ($request_method = 'OPTIONS') {
return 204;
}
#进行反向代理
proxy_pass http://localhost:[你的端口]/[方法路劲];
复制

Nginx做跨域处理的好处就是完全不用在后端或者前端代码 更能体现架构上的分离

需要注意的是

  1. 你必须可以访问localhost:80 看到nginx默认的首页
  2. 修改好配置文件(nginx.conf)需要重启Nginx加载配置(nginx.exe -s reload即可)
转载请注明出处或者链接地址:https://www.qianduange.cn//article/2772.html
标签
spring boot
评论
还可以输入200
共0条数据,当前/页
会员中心 联系我 留言建议 回顶部
复制成功!