AngularJS实现cookie跨域

前后端分离被越来越多的公司重视利用。然后带来的最棘手的问题就是。用户信息应怎样保存。

一、场景描写叙述

以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, OPTIONS
	response.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转为json
	String 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和其它站点数据”button就能够看到了
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
原文地址:https://www.cnblogs.com/gavanwanggw/p/6944350.html