前后端分离的Springboot项目解决跨域问题

相信很多朋友在写前后端分离的项目时候,前端项目向后端发请求抓数据时肯定会遇到跨域问题。最近我自己也遇到了这个问题今天就是来分享一下解决的方法。
首先,我在这里先说明一下。我这边的前端项目使用的是Vue框架搭配Element-UI后端是Springboot框架。

遇到的情况就是在前端使用Element-UI表单组件里进行表单提交向后端发请求时遇到了的跨域问题
下面是前端表单提交的代码

<script>
submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        console.log("submit")
                        this.$axios.get("http://localhost:9000/Client/hello"
                        ).then( (rep) => {
                            if(rep.data == "hello"){

                                alert('submit!');
                            }else {
                                alert("账号或者密码错误")
                            }
                            console.log(rep)
                        })
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            }
</script>

下图就是浏览器发请求时控制台里报的跨域问题:
已拦截跨源请求:同源策略禁止读取位于 http://localhost:9000/admin/hello 的远程
在这里插入图片描述
我在网上找到的解决方法呢主要有很多种(但都没有解决),例如:
1.使用注解@CrossOrigin
在Controller类或者方法体前添加@CrossOrigin(origins = “http://localhost:9000”, maxAge = 3600)注解
2.复写WebMvcConfigurerAdapter类

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                .maxAge(3600)
                .allowCredentials(true);
    }
}

3.配置Nginx反向代理,通过Filter手动添加响应头

public class HeaderFilter implements Filter {
 // private Logger logger = Logger.getLogger(HeaderFilter.class);

 public void doFilter(ServletRequest request, ServletResponse resp, FilterChain chain)
   throws IOException, ServletException {
  HttpServletResponse response = (HttpServletResponse) resp;
  response.setHeader("Access-Control-Allow-Origin", "http://106.14.135.196:88"); // 解决跨域访问报错
  response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
  response.setHeader("Access-Control-Max-Age", "3600"); // 设置过期时间
  response.setHeader("Access-Control-Allow-Credentials", "true");
  response.setHeader("Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept, client_id, uuid, Authorization");
  response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // 支持HTTP
                     // 1.1.
  response.setHeader("Pragma", "no-cache"); // 支持HTTP 1.0.
             // response.setHeader("Expires",
             // "0");
  chain.doFilter(request, resp);
 }

 public void init(FilterConfig filterConfig) {
 }

 public void destroy() {
 }
}

可是在我试了种种的方法后都没能解决我的问题,最后我在使用第二种方法时,我发现网上说复写的WebMvcConfigurerAdapter类其实已经弃用了(可能因为查看的帖子是2015年的),所以我就顺着复写Web配置类的这个思路找到了最终的解决方法:复写WebMvcConfigurer接口

@Configuration
public class WebConfig implements WebMvcConfigurer {
    //     跨域支持
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "DELETE", "PUT", "PATCH", "OPTIONS", "HEAD")
                .maxAge(3600 * 24);
    }
} 

猜你喜欢

转载自blog.csdn.net/JavaD0g/article/details/107923049