跨域访问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 @ 2022-09-02 17:27  九月!!  阅读(73)  评论(0)    收藏  举报