ajax服务器跨域问题

本文章只是一个简单的记录,具体可观看慕课网视频(转载)

cross.png

被调用方解决方案

1、应用服务器添加 Filter(第一种方案)

@SpringBootApplication
public class AjaxserverApplication {

    public static void main(String[] args) {
        SpringApplication.run(AjaxserverApplication.class, args);
    }

    @Bean
    public FilterRegistrationBean registerFilter() {
        
        FilterRegistrationBean bean = new FilterRegistrationBean();
        
        bean.addUrlPatterns("/*");
        bean.setFilter(new CrosFilter());
        
        return bean ;
    }
}

public class CrosFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // TODO Auto-generated method stub

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        // TODO Auto-generated method stub

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

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
    }
}

2、http服务器配置(第二种方案)


nginx.png

apache.png

调用方解决方案

1、http服务器配置


nginx.png

apache.png

注:http服务器是部署的中间件
转载慕课网视频

你可能感兴趣的:(ajax服务器跨域问题)