CORS on Nginx 实现JS跨域教程

什么是跨域

简单地理解就是因为JavaScript同源策略的限制,a.com 域名下的js无法操作b.com或是c.a.com域名下的对象。

同源是指相同的协议、域名、端口。

特别注意两点:

如果是协议和端口造成的跨域问题“前台”是无能为力的,
在跨域问题上,域仅仅是通过“协议+域名+端口”来识别,两个不同的域名即便指向同一个ip地址,也是跨域的。

跨域解决方案之CORS

CORS: 跨域资源共享(Cross-Origin Resource Sharing)

Nginx配置

对于简单请求,如GET,只需要在HTTP Response后添加Access-Control-Allow-Origin。
对于非简单请求,比如POST、PUT、DELETE等,浏览器会分两次应答。第一次preflight(method: OPTIONS),主要验证来源是否合法,并返回允许的Header等。第二次才是真正的HTTP应答。所以服务器必须处理OPTIONS应答。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
if ($request_method = 'POST') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
add_header 'Access-Control-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
}
if ($request_method = 'GET') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
add_header 'Access-Control-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
}

把上面配置放入nginx server配置中的location配置下即可实现跨域

配置详解

点我跳转

前台代码

此页面在oa.lilixin.top域下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="../easyui/jquery.min.js"></script>
</head>
<body>
<div >
<h1>
<a id="send">ajax</a>
</h1>
</div>
</body>
<script >
$("#send").click(function () {
$.ajax({
url : 'http://api.lilixin.top/cors/test',
type : "GET",
async : false,
success : function(data) {
alert(data)
}
});
})
</script>
</html>

后台代码

后台代码部署在api.lilixin.top下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* @author lilixin
* @description
* @create 2017-08-09 4:42 PM
**/
@Controller
@RequestMapping("cors")
public class CORSController{
private static final Logger logger = LoggerFactory.getLogger(CORSController.class);
@RequestMapping(value = "test", method = { RequestMethod.POST, RequestMethod.GET })
public @ResponseBody
String test(){
return "成功获取";
}

nginx实例配置

api配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
upstream api.lilixin.top {
server 127.0.0.1:8082;
}
server {
listen 80;
server_name api.lilixin.top;
#charset koi8-r;
access_log /logs/api.access.log myFormat;
location / {
root html;
index index.html index.htm;
proxy_pass http://api.lilixin.top;
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
#
# Custom headers and headers various browsers *should* be OK with but aren't
#
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
#
# Tell client that this pre-flight info is valid for 20 days
#
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
if ($request_method = 'POST') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
add_header 'Access-Control-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
}
if ($request_method = 'GET') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
add_header 'Access-Control-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
}
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}

oa配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
upstream oa.lilixin.top {
server 127.0.0.1:8081;
}
server {
listen 80;
server_name oa.lilixin.top;
#charset koi8-r;
access_log /logs/oa.access.log myFormat;
location / {
root html;
index index.html index.htm;
proxy_pass http://oa.lilixin.top;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
关注我的微信,共同分享与讨论!