案例cookie實現跨域
(我的博客裏有更新)
跨域,顧名思義,個人理解就是:任意兩個url只要協議、域名、端口有任何一個不同,都被當作是不同的域,相互訪問就會有跨域問題。
例如如下這一段代碼,在前端頁面中調試這個ajax所在的頁面,頁面路徑是http://localhost:8081/demo1/index.html,而要訪問的接口路徑是http://localhost:8082/demo2/login
$(function(){
$.ajax({
url: "http://localhost:8082/demo2/login",
type: "POST",
contentType: "application/json",
data: JSON.stringify({
"name": "tomcat",
password:"oracle"
}),
success: function(data) {
alert("success")
},
})
訪問結果坑定是報錯,提示的正是無法進行跨域訪問
那麼問題就是解決跨域問題了
跨域 要解決這個問題很簡單,
只要使頁面的前綴和接口的前綴一致就可以了,因此可以使用nginx進行反向代理。打開nginx目錄下的conf文件夾,在nginx.conf文件的配置如下:
1.修改nginx.config配置:
#默認監聽80端口,ip後面不加端口號默認就是80
listen 80;
#服務器地址
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
#項目根目錄,一般就是啓動頁
location / {
#項目所在目錄
root C:\Users\shengmengqi\WebstormProjects\angularJsFrame;
#假設across-domain.html的首頁,如果之後頁面中跳轉也是基於http://localhost/跳轉
index across-domain.html;
}
#作用:訪問的http://localhost:80/demo2/相當於一個代理url,實際訪問的是http://localhost:8082/demo2/;
location /demo2/{
proxy_pass http://localhost:8082/demo2/;
}
2.修改ajax中的請求url
$(function(){
$.ajax({
url: "http://localhost/demo2/login",
type: "POST",
contentType: "application/json",
data: JSON.stringify({
"name": "tomcat",
password:"oracle"
}),
success: function(data) {
alert("success")
},
})
3.啓動nginx.
將ngnix啓動起來,在任務管理器中是否有nginx進程,有的話說明啓動成功,如果沒有,可以查看nginx目錄下log文件夾中的error.log,看哪裏有問題進行修改,啓動成功後,在瀏覽器地址欄直接訪問localhost,這次結果就正確了。
ajax的請求請求其實是走了nginx代理服務器的.
是不是感覺有點像tomcat配置虛擬路徑的感覺啊
還有一種解決方案(前後端分離):
案例:業務上線以後,前端頁面出現了跨域問題,域名1.xxx.com 跨域訪問 2.xxx.com/login/的url,瀏覽器頁面產生問題
在2.xxx.com的nginx配置項中,添加如下請求頭
if ($http_origin ~* (http://1\.xxx\.com$)) {
add_header Access-Control-Allow-Headers 'Cookie,Set-Cookie,x-requested-with,content-type';
add_header Access-Control-Allow-Origin $http_origin ;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS';
}
大概解釋一下,就是從1.xxx.com域名發的請求,可以跨域到2.sss.xxx/login
在2.sss.com的nginx配置項中,添加如下請求頭
if ($http_origin ~* (http://1\.sss\.com$)) {
add_header Access-Control-Allow-Headers 'Cookie,Set-Cookie,x-requested-with,content-type';
add_header Access-Control-Allow-Origin $http_origin ;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS';
}
大概解釋一下,就是從1.sss.com域名發的請求,可以跨域到2.sss.com/bond
進行上面的配置以後,跨域問題解決,瀏覽器不報錯,但是又出現另一個問題,後端tomcat響應頭中,一直Set-Cookie,登陸業務一直錯誤,
確認前端代碼,有沒有支持跨域請求,需要在js代碼中添加一下代碼,讓前端支持跨域
$.ajax({
url: "xxxxxx",
// 將XHR對象的withCredentials設爲true
xhrFields:{
withCredentials:true
}});
解決方案三(這是大boss的方案:Nginx + Tomcat + HTTPS極速配置)
1.首先去阿里申請免費的https證書
1528815948944.pem;
1528815948944.key;
2.修改nginx配置文件 nginx.conf
#user nobody;
worker_processes 1;
#error_log logs/error.log notice;
#error_log logs/error.log info;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#tcp_nopush on;
keepalive_timeout 65;
#tomcat集羣的入口
upstream tomcat {
server 127.0.0.1:8180 ;
}
listen 80 ;
listen 443 ssl; # 監聽https 請求
server_name 127.0.0.1;#這裏是你的域名,要與下面tomcat裏的保持一致
# ssl 證書配置路徑(可花錢買)
ssl_certificate H://apache-tomcat-7.0.82//conf//1528815948944.pem;
ssl_certificate_key H://apache-tomcat-7.0.82//conf//1528815948944.key;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
location / {
#處理瀏覽器OPTIONS 預請求,默認返回200
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Credentials' true;
add_header 'Access-Control-Allow-Origin' "$http_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' 'application/json; charset=utf-8';
add_header 'Content-Length' 0;
return 200;
}
proxy_pass http://tomcat ;
#tomcat支持https 請求,須tomcat 更改相關配置
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-Proto https;
proxy_redirect off;
}
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias;
# root html;
# index index.html index.htm;
# }
#}
# HTTPS server
#
#server {
# listen 443 ssl;
# server_name localhost;
# ssl_certificate_key cert.key;
# ssl_session_timeout 5m;
# ssl_prefer_server_ciphers on;
# root html;
# index index.html index.htm;
# }
#}
3.進入tomcat,找到conf文件夾中的server.xml
找到<Connector port="8080" protocol="HTTP/1.1" 這一行,修改爲:
- <Connector port="8080" protocol="HTTP/1.1"
- connectionTimeout="20000"
- redirectPort="443"
- proxyPort="443" />
4.修改HOST裏的value值,我這裏修改爲:
- <Host name="<span style="color:#FF0000;">www.cjluzzl.cn</span>" appBase="webapps" <!--這裏的name要與nginx配置文件裏的server_name保持一致-->
- unpackWARs="true" autoDeploy="true">
- <Valve className="org.apache.catalina.valves.RemoteIpValve"
- remoteIpHeader="x-forwarded-for"
- remoteIpProxiesHeader="x-forwarded-by"
- protocolHeader="x-forwarded-proto" />
- </Host>
到這裏已經實現了前端跨域,要實現後端跨域還需加上以下配置:加個後端允許跨域
<!-- 接口跨域配置 -->
<mvc:cors>
<mvc:mapping path="/**"
allowed-origins="*"
allowed-methods="POST, GET, OPTIONS, DELETE, PUT"
allowed-headers="Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"
allow-credentials="true" />
</mvc:cors>
可在web.xml中添加,也可通過註解的方式允許跨域,我在這裏用mvc.xml方式.可以通過https實現跨域訪問啦.