解决跨域问题

解决跨域问题

配置跨域过滤器(通用)

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;

/**
 *配置了跨域请求的相关设置,允许指定的来源、请求头、请求方法,并设置最大有效时长。
 */
@Configuration
public class CorsConfig {

    // 当前跨域请求最大有效时长。这里默认1天
    private static final long MAX_AGE = 1800L;

    /**
     * 配置跨域过滤器
     *
     * @return CorsFilter实例
     */
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 设置允许的访问源地址与前端相连接
        corsConfiguration.addAllowedOrigin("*"); // 1 设置访问源地址与前端相连接
        corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头
        corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法
        corsConfiguration.setMaxAge(MAX_AGE);
        source.registerCorsConfiguration("/**", corsConfiguration); // 4 对接口配置跨域设置
        return new CorsFilter(source);
    }
}

若依框架跨域默认配置与通用跨域配置一致,且若依跨服配置在ruoyi-framework中的com.ruoyi.framework.config.ResourcesConfig 类中通过定义corsFilter来实现

posted @   戒爱学Java  阅读(13)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现

喜欢请打赏

扫描二维码打赏

了解更多

点击右上角即可分享
微信分享提示