美文网首页
SpringBoot轻松跨域

SpringBoot轻松跨域

作者: 蜜思1013 | 来源:发表于2019-04-17 21:48 被阅读0次

    1.项目结构,config包下放入一个配置类

    image.png

    2.WebMvcConfigurer配置类

    ![image.png](https://img.haomeiwen.com/i16112273/13fbf5da38ed6b13.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
    #2.WebMvcConfigurer配置类
    package com.springboot.mybatis.config;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.CorsRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
    
    @Configuration
    public class WebMvcConfigurer extends WebMvcConfigurerAdapter {
        //跨域配置
        @Bean
        public WebMvcConfigurer corsConfigurer() {
            return new WebMvcConfigurer() {
                @Override
                //重写父类提供的跨域请求处理的接口
                public void addCorsMappings(CorsRegistry registry) {
                    //添加映射路径
                    registry.addMapping("/**")
                            //放行哪些原始域
                            .allowedOrigins("*")
                            //是否发送Cookie信息
                            .allowCredentials(true)
                            //放行哪些原始域(请求方式)
                            .allowedMethods("GET", "POST", "PUT", "DELETE")
                            //放行哪些原始域(头部信息)
                            .allowedHeaders("*")
                            //暴露哪些头部信息(因为跨域访问默认不能获取全部头部信息)
                            .exposedHeaders("Header1", "Header2");
                }
            };
        }
    }
    

    3.然后前端就可以进行跨域访问了

    相关文章

      网友评论

          本文标题:SpringBoot轻松跨域

          本文链接:https://www.haomeiwen.com/subject/tljywqtx.html