springboot项目跨域问题解决

2021/5/6 11:01:17

本文主要是介绍springboot项目跨域问题解决,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

springboot项目跨域问题解决

单个配置跨域

添加注解@Crossorigin实现微粒级跨域

全局配置

  • 新建Webconfig类

  • //全局配置注解
    @Configuration
    //可采用@Crossorigin;实现微粒级跨域,全局跨域配置如下:
    public class WebConfig implements WebMvcConfigurer {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("*")
                    .allowedMethods("GET", "POST", "DELETE", "PUT", "OPTIONS")
                    .allowedHeaders("*")
                    .maxAge(3600 * 24);
        }
    }
    
  • 函数说明:

    addMapping:配置可被跨域访问的路径,'*'表示任意路径,也可以具体到直接请求路径。
    allowedOrigins:允许所有的请求域名访问我们的跨域资源,可以固定单条或者多条内容,"http://localhost:8088","null"
        如果出现如下异常
        `Caused by: java.lang.IllegalArgumentException: When allowCredentials is true, allowedOrigins cannot contain the special value "*"since that cannot be set on the "Access-Control-Allow-Origin" response header. To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead.`
    将allowedOrigins换成allowedOriginPatterns:
    allowCredentials: 响应头表示是否可以将对请求的响应暴露给页面。返回true则可以,其他值均不可以
    注意allowedOrigins(“*”):与allowCredentials(true)冲突
    allowedMethods:允许输入参数的请求方法访问该跨域资源服务器,如:POST、GET、PUT、OPTIONS、DELETE等。
    allowedHeaders:'*'允许所有的请求header访问,也可以自定义设置任意请求头信息
    maxAge:配置客户端缓存预检请求的响应的时间(以秒为单位)。默认设置为1800秒(30分钟)。
    


这篇关于springboot项目跨域问题解决的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程