AngularJS實現cookie跨域,angularjscookie
前後端分離被越來越多的公司重視利用,然後帶來的最棘手的問題就是,使用者資訊應如何儲存。
一、情境描述以Java為後台,AngluarJS做前端為例進行描述:當使用者在介面登入時,需把使用者資訊(如uid)存入後台JAVA系統中,用於前後端所處主域可能不同,所有採用常規的session進行儲存已不能滿足其業務情境。
解決方案:採用cookie進行儲存,當cookie被禁止後採用瀏覽器本機存放區localstorage。
採用cookie進行儲存時,會出現跨域問題(即AngularJS訪問JAVA端,需攜帶資訊存入到JAVA服務端cookie中)。
二、AngularJS執行個體AngularJS:
<pre name="code" class="javascript">function getAdustryController($scope,$http){$http.post('http://localhost/ajax/getAllIndustryCategoty.pt',{languageColumn:'name_eu'},{'withCredentials':true}).success(function(data){$scope.industries = data;});}
JAVA:
public String execute(){/* 要存入的cookie資訊 */Cookie cookie = new Cookie("test_test","321");cookie.setMaxAge(3600);response.addCookie(cookie);/* This is a part of security, you cannot do that. If you want to allow credentials then your Access-Control-Allow-Origin must not use *. You will have to specify the exact domain. */response.setHeader("Access-Control-Allow-Origin", "http://test.domain.cn"); //請求源response.setHeader("Access-Control-Allow-Methods","POST"); //請求方式POST, GET, OPTIONSresponse.setHeader("Access-Control-Max-Age", "3600"); //有效期間response.setHeader("Access-Control-Allow-Headers", "Content-Type, *"); //要求標頭類型response.setHeader("Access-Control-Allow-Credentials","true"); //是否支援cookie跨域SiteHandlerAction SiteHandler = (SiteHandlerAction) BeansFactory.getBean(SiteHandlerAction.class);List<IndustryCategory> list = SiteHandler.getAllIndustryCategory(); //所有的分類集合JSONArray jsonArray = JSONArray.fromObject(list); //將list轉為jsonString json = jsonArray.toString(); //轉為json字串//將字串寫進輸出資料流try {PrintWriter write = response.getWriter();write.print(json);write.close();} catch (IOException e) {e.printStackTrace();}return NONE;}三、Jquery執行個體:
$.ajax("http://localhost/ajax/getAllIndustryCategoty.pt",{type:"POST",data:{languageColumn:'name_eu'},xhrFields:{withCredentials: true},crossDomain::true,success:function(data, status, xhr){}});四、常用瀏覽器查看所有cookie資訊方式Google瀏覽器查看本機所有cookie資訊:依次點擊設定--進階選項--內容設定--cookies--選擇“顯示cookies和其他網站資料”按鈕就可以看到了
firefox瀏覽器查看本機所有cookie資訊:依次點擊設定--選項--隱私--移除單個Cookie
五、header資訊:
| Access-Control-Allow-Origin: <origin> | * |
授權的源控制 |
| Access-Control-Max-Age: <delta-seconds> |
授權的時間 |
| Access-Control-Allow-Credentials: true | false |
控制是否開啟與Ajax的Cookie提交方式 |
| Access-Control-Allow-Methods: <method>[, <method>]* |
允許請求的HTTP Method |
| Access-Control-Allow-Headers: <field-name>[, <field-name>]* |
控制哪些header能發送真正的請求 |
參考文章:http://my.oschina.net/blogshi/blog/303758