前后端交互解决跨域问题

前后端交互解决跨域问题

1、 开发中,使用nginx反向代理问题,涉及set-cookie、cookie问题的使用fiddler抓包进行更改设置

2、 上线的时候

后台与前端页面同源,则可以忽略跨域问题。

后台与前端页面不同源

  1. CORS资源共享,使用nginx反向代理,注意前端页面的url应与反向代理的url同域

  2. Ajax请求中设置xhrFields:{withCredentials:true},后台需要设置Access-Control-Allow-Credentials: true,需要注意的是服务器不得设置 Access-Control-Allow-Origin的值为,否则浏览器将会抛出The value of the ‘Access-Control-Allow-Origin’ header in the response must not be the wildcard ‘‘ 错误。

​ 3. 反向代理

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
53
server {
listen 80;
server_name carrie.lifengjun.xin;
root /usr/local/www/website;
index index.html index.htm index.php;
listen 443
ssl on;
ssl_certificate cert/214210586120730.pem;
ssl_certificate_key cert/214210586120730.key;
ssl_session_timeout 5m;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;

#proxy_set_header Host $host;
location /news
{
proxy_pass https://www.eunieunieuni.xin/news;
proxy_set_header Cookie $http_cookie;
proxy_set_header Host lifengjun.xin;
proxy_cookie_domain lifengjun.xin www.eunieunieuni.xin;
#add_header 'Access-Control-Allow-Origin' '*';
#add_header Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept";
#add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Credentials' 'true';
#
# 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';
#
# 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';
}
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';
}
}
}

使用fiddler反向代理

1