解决前后端跨域问题

方法一 CORS:

java服务端添加如下代码即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
String[] allowDomain = {"http://loanstatic.gs.youyuwo.com",
"http://loanstatic.youyuwo.com", "https://loanstatic.youyuwo.com",
"http://gjj.youyuwo.com", "https://gjj.youyuwo.com",
"http://www.huishuaka.com", "https://www.huishuaka.com",
"http://loan.huishuaka.com", "https://loan.huishuaka.com"};
Set<String> allowedOrigins= new HashSet<>(Arrays.asList(allowDomain));
String originHeader = request.getHeader("Origin");

if (allowedOrigins.contains(originHeader)) {
response.setHeader("Access-Control-Allow-Origin", originHeader);
response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE");
response.setHeader("Access-Control-Allow-Headers", "Origin,No-Cache,X-Requested-With,If-Modified-Since,Pragma,Last-Modified,Cache-Control,Expires,Content-Type,X-E4M-With,userId,token");//表明服务器支持的所有头信息字段
response.setHeader("Access-Control-Allow-Credentials", "true"); //如果要把Cookie发到服务器,需要指定Access-Control-Allow-Credentials字段为true;
response.setHeader("XDomainRequestAllowed", "1");
response.setHeader("Access-Control-Max-Age", "3600");
response.setContentType("application/json;charset=UTF-8");
}

方法二 CORS(推荐):

在nginx配置文件添加配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
if ($http_origin ~ https://(.*).youyuwo.com){
set $allow_url $http_origin;
}
if ($http_origin ~ https://(.*).huishuaka.com){
set $allow_url $http_origin;
}
if ($http_origin ~ https://(.*).youyuxin.com){
set $allow_url $http_origin;
}
add_header Access-Control-Allow-Origin $allow_url;
add_header Access-Control-Allow-Headers Origin,No-Cache,X-Requested-With,If-Modified-Since,Pragma,Last-Modified,Cache-Control,Expires,Content-Type,X-E4M-With,userId,token;
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS;
add_header XDomainRequestAllowed 1;
add_header Access-Control-Max-Age 3000;

方法三:

使用jsonp


解决前后端跨域问题
https://www.wekri.com/java解决前后端跨域问题/
Author
Echo
Posted on
January 25, 2018
Licensed under