hjr-JAVA:跨域

有時可能本地正常的項目放到服務器報跨域相關錯誤

前端瀏覽器報 Access-Control-Allow-Origin 相關錯誤

兩種:接口訪問(post,get)和靜態資源請求都可能報錯

首先,寫一個攔截器攔截所有請求,請求就是request,然後在返回response添加頭部

   PrintWriter out = response.getWriter();
        ResourceBundle resource = ResourceBundle.getBundle("test");//test爲配置文件test.properties的名字,放在src下的屬性文件
        String key = resource.getString("baseurl");
		//這裏baseurl爲服務器域名+端口   或者 *
        response.setHeader("Access-Control-Allow-Origin", key);
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
        response.setContentType("application/json; charset=UTF-8");

上面的配置,第一個是允許跨域,如果用*代表允許所有跨域
報的各種錯誤,分別對應缺少上面那幾個header或者header中的某個屬性,把我這個全寫上能保證不報錯

sessionId每次都變化,獲取session值報空指針錯誤

有時會發現跨域請求每次sessionId不一直,導致獲取session爲null
前端ajax請求需要加上 ,意思是允許傳送cookie,裏面有sessionid可以 保持session一致,後臺的這個response.setHeader("Access-Control-Allow-Credentials", "true");同意前端傳送cookie,要配合前端一起寫。
並且如果你用了這個方法,那麼response.setHeader("Access-Control-Allow-Origin", *);這個配置就不可以用*了必須改爲服務器域名+端口
xhrFields: {
withCredentials: true
}

$.ajax({
	  	type:"POST",
	  	url:"",
	  	dataType:"json",
		xhrFields: {
			withCredentials: true
		},...
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章