博主首页

处理前端人员提出的接口跨域问题/CORS error

   手机端调用接口没有问题、但是前端人员说访问存在跨域问题、无法正常调用

    public EiInterfaceQZPO toMail(String biz,HttpServletResponse response){
        response.setHeader("Access-Control-Allow-Origin", "*");  
          
        response.setHeader("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");  
      
        response.setHeader("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");  
      
        response.setHeader("X-Powered-By","Jetty"); 

设置返回头信息后前端可以正常访问了、接口过多的话、使用过滤器进行处理、、、、、

 

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class SimpleCORSFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        HttpServletResponse res2 = (HttpServletResponse) res;
        HttpServletRequest req2 = (HttpServletRequest) req;
        String origin = req2.getHeader("Origin");
        if (!org.springframework.util.StringUtils.isEmpty(origin)) {
            //带cookie的时候,origin必须是全匹配,不能使用*
            res2.addHeader("Access-Control-Allow-Origin", origin);
        }
        res2.addHeader("Access-Control-Allow-Methods", "*");
        String headers = req2.getHeader("Access-Control-Request-Headers");
        // 支持所有自定义头
        if (!org.springframework.util.StringUtils.isEmpty(headers)) {
            res2.addHeader("Access-Control-Allow-Headers", headers);
        }
        res2.addHeader("Access-Control-Max-Age", "3600");
        // enable cookie
        res2.addHeader("Access-Control-Allow-Credentials", "true");
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}

}

 

springboot项目处理

 

@Configuration
public class WebConfigCORS {


    /**
     * 跨域支持
     */
    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilterRegistration() {
        FilterRegistrationBean<CorsFilter> registration = new FilterRegistrationBean<>();
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        // #允许向该服务器提交请求的URI,*表示全部允许
        config.addAllowedOrigin(CorsConfiguration.ALL);
        // 允许cookies跨域
        config.setAllowCredentials(true);
        // #允许访问的头信息,*表示全部
        config.addAllowedHeader(CorsConfiguration.ALL);
        // 允许提交请求的方法,*表示全部允许
        config.addAllowedMethod(CorsConfiguration.ALL);
        source.registerCorsConfiguration("/**", config);
        registration.setFilter(new CorsFilter(source));
        registration.addUrlPatterns("/*");
        registration.setName("corsFilter");
        registration.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return registration;
    }
}

 

posted @ 2019-04-16 15:38  笑~笑  阅读(2303)  评论(0编辑  收藏  举报