Ajax跨域問題:跨域請求設定withCredentials
轉:http://www.cnblogs.com/zhangcybb/p/6594991.html
最近在做運動城專案,這一個專案下面有多個子專案,如主資料專案,pos專案等。主資料專案的域名為www.topmall.com,POS專案的域名為pos.topmall.com。即兩個專案的主域名相同,子域名不相同。
我們的登陸認證是放在主資料專案的,即進入POS專案如果檢測未登陸,是先要呼叫主資料的一個登陸介面登陸後才可以訪問的。這時候跨域問題就出現了,進入POS專案之後跳出登陸框,輸入使用者名稱密碼請求主資料的http://www.topmall.com/signin進行登陸,看到返回的response裡面也有Set-cookie,但是再次請求POS專案的
查詢資料才知道登陸請求的主資料專案與POS專案不屬於同一個子域,即存在跨域,跨域請求想要帶上cookies必須在請求頭裡面加上{crossDomain: true, xhrFields: {withCredentials: true}}設定,於是在index介面加上了如下程式碼:
<script>
$(function () { //, headers: { 'x-requested-with': 'XMLHttpRequest' }
$.ajaxSetup({crossDomain: true, xhrFields: {withCredentials: true}});
});
</script>
然後在後臺程式碼返回response時做如下處理:
private boolean recharge(HttpServletRequest request, HttpServletResponse response) throws Exception {
String url = request.getHeader("Origin");
logger.debug("Access-Control-Allow-Origin:" + url);
if (!StringUtils.isEmpty(url)) {
String val = response.getHeader("Access-Control-Allow-Origin");
if (StringUtils.isEmpty(val)) {
response.addHeader("Access-Control-Allow-Origin", url);
response.addHeader("Access-Control-Allow-Credentials", "true");
}
}
return true;
}
再次訪問,發現請求頭已經可以攜帶cookies。
——————————————————————————————————————————
參考以上資訊對自己的問題進行了相應修改還是報錯
The 'Access-Control-Allow-Origin' header contains the invalid value 'sysadmin.sydwl.com'. Origin 'http://sysadmin.sydwl.com' is therefore not allowed access.
原因是後端的response.addHeader(“Access-Control-Allow-Origin”,”sysadmin.sydwl.com”);要改成
response.addHeader(“Access-Control-Allow-Origin”,”http://sysadmin.sydwl.com“);
或者response.addHeader(“Access-Control-Allow-Origin”,”*”);
@SuppressWarnings("unchecked")
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
response.addHeader("Access-Control-Allow-Origin","http://sysadmin.sydwl.com");
response.addHeader("Access-Control-Allow-Credentials", "true");
filterChain.doFilter(request, response);
}
總結:
問題雖然解決了,但裡面的所涉及的東西不是很懂,只能有空再瞭解了