跨域访问cros

项目前后端分离时,会出现跨域访问,就需要解决cros跨域请求问题

1.加注解

在请求层上面加上@CrossOrigin,就可以实现跨域并访问所有的资源了。

2.写配置类重写方法

import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

//@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
//        CorsRegistration registration = new CorsRegistration(pathPattern);
        registry.addMapping("/**")  //允许跨域访问的路径
        .allowedOrigins("*")    //运行访问资源
        .allowedMethods("POST","GET","PUT","OPTIONS","DELETE")
        .maxAge(168000) //预检间隔时间
        .allowedHeaders("*")    //允许头部设置
        .allowCredentials(true);    //是否发送cookie
    }
}
posted @   九月!!  阅读(67)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示