SpringBoot工程如何实现跨域请求

2022-06-16 12:48:52

1.问题描述

最近在使用SpringBoot框架开发Web层项目时遇到的一个小问题,整体项目采用前后端分离模式进行开发,将后端springboot项目打成jar 部署到服务器中,前端发送请求遇到跨域错误问题。

2.解决方法:CORS解决跨域问题

为了解决浏览器同源问题,W3C 提出了跨源资源共享,即 CORS(Cross-Origin Resource Sharing)。

CORS 做到了如下两点:

1:不破坏即有规则
2:服务器实现了 CORS 接口,就可以跨源通信

Springboot配置CORS

import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.web.cors.CorsConfiguration;import org.springframework.web.cors.UrlBasedCorsConfigurationSource;import org.springframework.web.filter.CorsFilter;@ConfigurationpublicclassCorsConfig{private CorsConfigurationbuildConfig(){
        CorsConfiguration corsConfiguration=newCorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.setAllowCredentials(true);return corsConfiguration;}@Beanpublic CorsFiltercorsFilter(){
        UrlBasedCorsConfigurationSource source=newUrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**",buildConfig());returnnewCorsFilter(source);}

3.内容含义

1:Access-Control-Allow-Headers: 服务器允许使用的字段,定位为"*"代表所有的都可以。
2:Access-Control-Allow-Methods: 真实请求允许的方法,定位为"*"代表所有的都可以。例如:“POST”, “GET”, “PUT”, “OPTIONS”, “DELETE”。
3:Access-Control-Allow-Credentials: 是否允许用户发送、处理 cookie
4:Access-Control-Max-Age: 预检请求的有效期,单位为秒。有效期内,不会重复发送预检请求,这个可以在代码中配置,也可以不配置。
5:定义一个过滤器:CorsFilter, 声明CORS 配置对所有接口都有效
  • 作者:小李的日常
  • 原文链接:https://blog.csdn.net/lihaoyiding/article/details/105054474
    更新时间:2022-06-16 12:48:52