300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > Ajax跨域请求后台无法识别session id的解决方式[withCredentials = true]

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

时间:2022-08-21 08:12:46

相关推荐

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 idxhrFields: {withCredentials: true}})

或者在ajax中添加上参数

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

附angularjs的$http的配置方式:

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。