Ajax跨域请求后台无法识别session id的解决方式[withCredentials = true]

原始请求:

$.get('http://localhost/getData').success(function(data){
	console.log(data);
})

对应的接口:

  @RequestMapping(value = "/getData", method = RequestMethod.GET)
  public Object update(HttpSession session) {
    if(session.getAttribute("user") == null){
      return "未登錄";
    }
    return "測試";
  }

通过debug输出发现,ajax请求一直没有session id,所以无论怎么登录,最终访问这个接口,都取不到user。


解决方式:

全局设置ajax的withCredentials为true
$.ajaxSetup({
  // 設置Ajax請求可以識別cookie session id
  xhrFields: {
    withCredentials: true
  }
})

或者在ajax中添加上参数

$.ajax({
	url : 'http://localhost/getData',
	xhrFields: {
           withCredentials: true
      	},
})

附angularjs的$http的配置方式:

angular.module('app').config(function ($httpProvider) {
	$httpProvider.defaults.withCredentials = true;
})

猜你喜欢

转载自blog.csdn.net/a873217486/article/details/78625684