First, what is the cross-domain
Cross-domain is to limit the browser's same-origin policy for JavaScript
Second, under what circumstances will have cross-domain
Different domain | wwww.baidu.com | www.jd.com |
The same domain name, different port access | wwww.baidu.com:8080 | wwww.baidu.com:8081 |
The same level domain, two domain names do not | map.baidu.com | pan.baidu.com |
Third, why have cross-domain issues
because the problem is browser cross-domain security restrictions for one ajax request: ajax request initiated by a page, only the current page domain name the same path, which can effectively prevent cross station attack.
Therefore: cross-domain problem is a limitation for the ajax.
Fourth, how to solve cross-domain problems
1, configure the domain name and port number to access the file nginx.conf under nginx, such as:
server {
listen 80;
server_name aaaa.com;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
location / {
proxy_pass http://127.0.0.1:8888;
proxy_connect_timeout 600;
proxy_read_timeout 600;
}
}
server {
listen 80;
server_name bbbb.com;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
location / {
proxy_pass http://127.0.0.1:9999;
proxy_connect_timeout 600;
proxy_read_timeout 600;
}
}
在nginx的配置文件中配置了两个域名,aaaa.com和bbbb.com,分别通过8888和9999两个端口来访问它们,端口的域名都要是项目中使用的域名,不可随意取。
2、在hosts文件中把域名和对应的ip配置好,如:
127.0.0.1 aaaa.com
127.0.0.1 aaaa.com
这里配置的域名要和ngnix中配置的域名相同
3、在项目中定义一个过滤器,让数据可以进行跨域访问
@Configuration
public class LeyouCorsConfig {
@Bean
public CorsFilter corsFilter(){
//初始化Cors配置对象
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowCredentials(true);//允许携带cookie
configuration.addAllowedOrigin("http://manage.leyou.com");//允许这个域名进行跨域访问
configuration.addAllowedHeader("*");//允许携带任何头信息
configuration.addAllowedMethod("*");//代表所有的请求方法:POST GET PUT Delete
//初始化Cors配置源对象
UrlBasedCorsConfigurationSource configurationSource = new UrlBasedCorsConfigurationSource();
configurationSource.registerCorsConfiguration("/**", configuration);//所有路径都需要解决跨域路径访问问题
//返回CorsFilter
System.out.println("可以进行跨域操作了=============================");
return new CorsFilter(configurationSource);
}
}