axios 解決cookie跨域問題

1.問題背景:
前端使用vue,axios 調用服務端api,
前端域名:aaa.bb.u.cn
後端域名:server.ss.u.cn
發現後端寫完session,cookie後,瀏覽器獲取不到session,查看瀏覽器也沒有cookie,此時已經確保後端的session和cookie是種成功的
並且,再服務端的配置中,已經設置了跨域支持,如下:

location ~ /*.php$ {
add_header ‘Access-Control-Allow-Origin’ KaTeX parse error: Double superscript at position 62: …Allow-Methods' '̲GET,POST,OPTION…request_method = ‘OPTIONS’) {
add_header ‘Access-Control-Max-Age’ 86400;
add_header ‘Content-Type’ ‘text/plain; charset=utf-8’;
add_header ‘Content-Length’ 0;
return 204;
}

  fastcgi_index index.php;
  fastcgi_read_timeout 300;
  include fastcgi.conf;
  fastcgi_pass 127.0.0.1:9101;

}

2.解決如下:
因爲前端使用了基於promise的http庫,axios,
有跨域問題時請求如下:
this.axios({
url:Global.originUrl+’/proj’,
method:‘GET’
}).then((response) => {
//do something
});

需要添加withCredentials:true, 即支持跨域,默認是false

如下:
this.axios({
url:Global.originUrl+’/proj’,
withCredentials:true,
method:‘GET’
}).then((response) => {
//do something
});

yes,yes,yes 成功

3.總結一下跨域
(1)前端
(1.1)ajax jsonp
(1.2) axios withCredentials:true
(2)服務端
add_header ‘Access-Control-Allow-Origin’ KaTeX parse error: Double superscript at position 62: …Allow-Methods' '̲GET,POST,OPTION…request_method = ‘OPTIONS’) {
add_header ‘Access-Control-Max-Age’ 86400;
add_header ‘Content-Type’ ‘text/plain; charset=utf-8’;
add_header ‘Content-Length’ 0;
return 204;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章