转载-在 SpringBoot 中全局设置允许跨域请求

本文介绍前后端分离的概念及其实现方式,并探讨其优缺点。通过Spring Boot配置示例,展示了如何解决跨域访问问题,确保前端能顺利调用后端接口。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载出处 https://blog.youkuaiyun.com/larger5/article/details/79805617

一、前言

现在在团队做的项目都是前后端分离的,借助 swagger 进行前后端合作 
① 后台负责写数据处理的接口 
② 前台负责解析 JSON、设计界面

要实现接口可以给前端访问,还要设置允许跨域访问接口,正式本文的重点

前后端分离优缺点: 
一、为什么要前后端分离: 
1.后台接口可以 pc、app、pad 多端适应 
2.前端 SPA 开发模式开始流行 
3.前后端开发职责不清(如 JSP/thymeleaf/freemarker/Django 模板引擎渲染数据,到底是谁的工作?) 
4.前后端互相等待,不能同时进行开发 
5.前端一直配合着后端,能力受限 
6.后台开发语言和模板高度耦合 
二、前后端分离缺点 
1.前后端学习门槛增加 
2.数据依赖导致文档重要性增加 
3.前端工作量加大 
4.SEO 的难度加大(ajax大量使用)

由于浏览器的安全性限制,不允许AJAX访问 协议不同、域名不同、端口号不同的 数据接口, 
浏览器认为这种访问不安全

二、代码

package com.zcw.conf;

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;

/**
 * 实现基本的跨域请求
 * @author linhongcun
 *
 */
@Configuration
public class CorsConfig {
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*"); // 允许任何域名使用
        corsConfiguration.addAllowedHeader("*"); // 允许任何头
        corsConfiguration.addAllowedMethod("*"); // 允许任何方法(post、get等)
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig()); // 对接口配置跨域设置
        return new CorsFilter(source);
    }
}

三、其他

以上的代码基本是常识了,记录一下, 
Ajax 请求示例:

<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <script src="js/jquery-1.7.2.js"></script>
    <script type="text/javascript">
        function upd() {
            $.ajax({
                type: "get",
                data: "a=1",
                url: "http://120.79.197.131:8080/user/getAllUser",
                success: function(result) {
                    console.log(result);
                }
            });
        }
    </script>
    <body>
        <!--获取-->
        <button id="btn2" onclick="upd()">Get request 获取</button>
    </body>

</html>

参考文章 
SpringBoot下如何配置实现跨域请求?

### SpringBoot 配置请求的最佳实践及方法 在Spring Boot中,支持请求(CORS)的配置可以通过多种方式实现。以下是一些常见的最佳实践及方法: #### 1. 全局配置方式 通过创建一个 `CorsConfigurationSource` 并将其注册到 `UrlBasedCorsConfigurationSource` 中,可以全局地为所有接口启用支持。以下是一个示例代码[^2]: ```java @Configuration public class CorsConfig { @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); // 允许发送凭据,例如Cookie或Authorization Header config.addAllowedOriginPattern("*"); // 允许任意访问接口 config.addAllowedHeader("*"); // 允许所有头部信息 config.addAllowedMethod("*"); // 允许所有请求方法 source.registerCorsConfiguration("/**", config); // 应用于所有路径 return new CorsFilter(source); } } ``` #### 2. 控制器级别配置 如果只需要为特定的控制器或方法启用支持,可以使用 `@CrossOrigin` 注解。以下是一个示例[^2]: ```java @RestController @RequestMapping("/api") @CrossOrigin(origins = "http://example.com", allowCredentials = "true", allowedHeaders = "*") public class MyController { @GetMapping("/data") public ResponseEntity<String> getData() { return ResponseEntity.ok("Cross-origin data"); } } ``` #### 3. 处理OPTIONS预检请求 为了确保浏览器发出的 OPTIONS 请求不会被安全框架拦截,可以在 Spring Security 配置中明确允许 OPTIONS 请求[^3]: ```java @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.cors().and() .authorizeRequests() .antMatchers(HttpMethod.OPTIONS, "/**").permitAll(); // 明确允许OPTIONS请求 } @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowedOrigins(Collections.singletonList("*")); configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS")); configuration.setAllowedHeaders(Arrays.asList("*")); configuration.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; } } ``` #### 4. 自动处理预检请求 Spring Boot 的 CORS 支持会自动处理预检请求(OPTIONS)。当客户端发起预检请求时,服务器会检查请求头中的 `Origin` 和 `Access-Control-Request-Method` 等字段,并返回相应的响应头[^4]。以下是一个判断预检请求的源码示例[^4]: ```java public static boolean isPreFlightRequest(HttpServletRequest request) { return HttpMethod.OPTIONS.matches(request.getMethod()) // 判断是否是OPTIONS请求 && request.getHeader("Origin") != null // 检查是否存在Origin头 && request.getHeader("Access-Control-Request-Method") != null; // 检查是否存在Access-Control-Request-Method头 } ``` #### 5. 配置文件方式 除了代码配置,还可以通过 `application.properties` 或 `application.yml` 文件进行简单的配置[^1]: ```properties spring.mvc.dispatch-options-request=true ``` 该配置可以让 Spring MVC 自动处理 OPTIONS 请求,从而简化预检的处理逻辑。 --- ### 总结 Spring Boot 提供了灵活的配置方式,开发者可以根据实际需求选择全局配置、局部配置或结合安全框架的方式。无论是通过注解、Java 配置类还是配置文件,都可以高效地解决问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值