跨域

什么是跨域?

浏览器从一个域名的网页去请求另一个域名的资源时,域名、端口、协议任一不同,都是跨域
所以跨域只能出现在前端浏览器,这是浏览器行为。后端之间的服务调用是不会出现跨域的。
域名:
主域名不同 http://www.baidu.com/index.html –>http://www.sina.com/test.js
子域名不同 http://www.666.baidu.com/index.html –>http://www.555.baidu.com/test.js
域名和域名ip http://www.baidu.com/index.html –>http://180.149.132.47/test.js
端口:
http://www.baidu.com:8080/index.html–> http://www.baidu.com:8081/test.js
协议:
http://www.baidu.com:8080/index.html–> https://www.baidu.com:8080/test.js
备注:
1、端口和协议的不同,只能通过后台来解决
2、localhost和127.0.0.1虽然都指向本机,但也属于跨域

解决办法:通过设置响应头

所有与跨域请求相关的HTTP头部都以Access-Control-开始, 下面是它们的详细信息
1.Access-Control-Allow-Origin (必选)
所有有效的跨域响应都必须包含这个请求头, 没有的话会导致跨域请求失败. 它的值可以是请求中的Origin的值, 也可以设置为*来表示可以响应所有来源的请求.
2.Access-Control-Allow-Credentials (可选)
默认情况下跨域请求不会携带cookies信息. 如果需要请求携带cookies信息, 则需要将这个值设置为true, 如果不需要就不要设置这个值, 而不是将它设置为false.
这个请求头需要与 [withCredentials](#XMLHttprequest 的 withCredentials 属性) 配合使用. 只有两个值都设置为true的时候才能够在请求中携带cookies信息. 当withCredentials设置为true, 而响应中不包含Access-Control-Allow-Credentials时, 请求会发生错误.
3.Access-Control-Expose-Headers (可选)
XMLHttpRequest2对象上的getResponseHeader()方法可以让你获取到响应中头部信息, 但在跨域请求中,你只能获取到以下信息
Cache-Control
Content-Language
Content-Type
Expires
Last-Modified
Pragma
如果你希望客户端能过获取其他的头部信息, 可以设置这个值.

所有解决办法都是通过设置响应头的原理

1.设置Filter拦截器

@WebFilter("/*")
public class CorsFilter implements Filter{

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //设置跨域请求
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
        response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "POST, GET, DELETE, PUT");
        response.setHeader(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "3628800");

        System.out.println("设置跨域请求");
        filterChain.doFilter(servletRequest, response);
    }

    @Override
    public void destroy() {

    }
}

2.设置@CrossOrigin(origins = "/*")注解

3.设置MVCConfiguration

@Configuration
public class ResourceConfigration extends WebMvcConfigurerAdapter {
    @Value("${spring.resources.static-locations}")
    private String resourceLocation;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/video/**").addResourceLocations(resourceLocation);
        super.addResourceHandlers(registry);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry){
        registry.addMapping("/home/hello/**")
                .allowedOrigins("*");
    }
}
原文地址:https://www.cnblogs.com/lanqi/p/10132044.html