AngularJS實現cookie跨域

來源:互聯網
上載者:User

AngularJS實現cookie跨域
前後端分離被越來越多的公司重視利用,然後帶來的最棘手的問題就是,使用者資訊應如何儲存。
一、情境描述以Java為後台,AngluarJS做前端為例進行描述:當使用者在介面登入時,需把使用者資訊(如uid)存入後台JAVA系統中,用於前後端所處主域可能不同,所有採用常規的session進行儲存已不能滿足其業務情境。
解決方案:採用cookie進行儲存,當cookie被禁止後採用瀏覽器本機存放區localstorage。
採用cookie進行儲存時,會出現跨域問題(即AngularJS訪問JAVA端,需攜帶資訊存入到JAVA服務端cookie中)。
二、AngularJS執行個體AngularJS:


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 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: | * 授權的源控制
Access-Control-Max-Age: 授權的時間
Access-Control-Allow-Credentials: true | false 控制是否開啟與Ajax的Cookie提交方式
Access-Control-Allow-Methods: [, ]* 允許請求的HTTP Method
Access-Control-Allow-Headers: [, ]* 控制哪些header能發送真正的請求


 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.