跨域
什么叫跨域
什么是跨域(摘要网络)
要了解跨域,先要说说同源策略。同源策略是由 Netscape 公司提出的一个著名的安全策略,所有支持 JavaScript 的浏览器都会使用这个策略。所谓同源是指,域名,协议,端口相同。当页面在执行一个脚本时会检查访问的资源是否同源,如果非同源,那么在请求数据时,浏览器会在控制台中报一个异常,提示拒绝访问。
同源策略一般又分为以下两种:
DOM同源策略:禁止对不同源页面DOM进行操作。这里主要场景是iframe跨域的情况,不同域名的iframe是限制互相访问的。XmlHttpRequest同源策略:禁止使用XHR对象向不同源的服务器地址发起HTTP请求。
现状跨域访问的作用
限制跨域资源访问的作用可从服务器和客户端两个方面进行分析:
1、对于服务器,当收到一个请求时,会检查该请求来源,如果来源的客户端页面自己无法识别,而且服务器的数据又是比较敏感的,则可能做出限制或者拒绝访问(例如,黑客对服务器的攻击)。
2、对于客户端,浏览器的同源策略可限制对跨域资源的访问,若其与服务器的域不相同,则浏览器可能进行限制甚至拒绝访问(例如,黑客通过让你访问他的服务器数据来攻击你的客户端页面)。
跨域访问失败时,实际上浏览器发送请求成功,浏览器也接收到了响应,但是它会限制xmlhttprequest接受响应并在js控制台报错。
那么,到底什么是跨域
现实工作开发中经常会有跨域的情况,因为公司会有很多项目,也会有很多子域名,各个项目或者网站之间需要相互调用对方的资源,避免不了跨域请求。
解决跨域
package com.lei.config;
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;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class WebConfig{
@Bean
public CorsFilter corsFilter() {
final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
final CorsConfiguration corsConfiguration = new CorsConfiguration();
/*是否允许请求带有验证信息*/
corsConfiguration.setAllowCredentials(true);
/*允许访问的客户端域名*/
corsConfiguration.addAllowedOrigin("*");
/*允许服务端访问的客户端请求头*/
corsConfiguration.addAllowedHeader("*");
/*允许访问的方法名,GET POST等*/
corsConfiguration.addAllowedMethod("*");
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(urlBasedCorsConfigurationSource);
}
}