Spring Boot 解决跨域问题(CORS 配置教程),WebMvcConfig addCorsMappings 方法配置跨域

望舒的头像
望舒
标签:
Spring Boot跨域Spring Boot CORS配置跨域请求解决方案前后端分离跨域java

在前后端分离开发中,前端项目通常通过 浏览器 调用后端接口。由于浏览器的 同源策略 限制,如果协议、域名、端口任意一项不同,就会出现 跨域请求问题(CORS Issue)。 为了保证前后端能够正常通信,我们需要在项目中开启跨域配置。

跨域问题的解决方案

省流,直接亮代码

复制
展开
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Slf4j
@Configuration
@ControllerAdvice
public class WebMvcConfig implements WebMvcConfigurer {

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

作者:https://blog.xn--rpv331d.com/望舒

链接:https://blog.xn--rpv331d.com/望舒/blog/102

转载请保留文章出处...

No data
No data