• springboot配置请求跨域问题



    import
    org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; /** * Created by myz on 2017/7/10. * * 设置跨域请求 */ @Configuration public class CorsConfig { private CorsConfiguration buildConfig() { CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedOrigin("*"); // 1 设置访问源地址 corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头 corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法 return corsConfiguration; } @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", buildConfig()); // 4 对接口配置跨域设置 return new CorsFilter(source); } }

     第二种配置方法

    import java.io.IOException;
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.stereotype.Component;
    
    /**
     * Created by myz on 2017/7/10.
     *
     * 设置跨域请求
     */
    @Component
    public class CorsConfig implements Filter{
    
        @Override
        public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
                throws IOException, ServletException {
            HttpServletResponse response=(HttpServletResponse)res;
            response.setHeader("Access-control-Allow-Origin", "*");
            response.setHeader("Access-control-Allow-Credentials", "true");
            response.setHeader("Access-control-Allow-Methods", "*");
            response.setHeader("Access-control-Max-Age", "3600");
            response.setHeader("Access-control-Allow-Headers", "Content-Type,Access-Token");
        }
        
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
        }
    
    
        @Override
        public void destroy() {
        }
        
    }
  • 相关阅读:
    分页封装实用工具类及其使用方法
    Oracle
    [置顶] Android高德地图显示气泡框
    设计模式 笔记 观察者模式
    数据质量,中国希望
    谁更胜一筹:技术解析 Google App Engine 和 Amazon EC2
    GZIP Http Servlet Response
    谁更胜一筹:技术解析 Google App Engine 和 Amazon EC2
    腾讯对外发布微博开放平台 API
    GZIP Http Servlet Response
  • 原文地址:https://www.cnblogs.com/yuhuiqing/p/10692854.html
Copyright © 2020-2023  润新知