您好,欢迎访问一九零五行业门户网

附带cookie如何实现ajax跨域请求

本篇文章给大家带来的内容是关于附带cookie如何实现ajax跨域请求,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
在项目的实际开发中,我们总会遇到前后端分离的项目,在这样的项目中,跨域是第一个要解决的问题,除此之外,保存用户信息也是很重要的,然而,在后台保存用户信息通常使用的session和cookie结合的方法,而在前端的实际情况中,跨域产生的ajax是无法携带cookie信息的,这样导致了session和cookie的用户信息储存模式受到影响,该怎样去解决这样一个问题呢,通过查阅资料,我这里以angularjs的$http中的ajax请求来举例子。
首先,在后台我使用的servlet的filter拦截所有的请求,并设置请求头:
// 解决跨越问题
response.setheader("access-control-allow-origin", "*"); response.setheader("access-control-allow-methods", "*"); response.setheader("access-control-max-age", "3600"); response.setheader("access-control-allow-headers", "dnt,x-mx-reqtoken,keep-alive,user-agent,x-requested-with,if-modified-since,cache-control,content-type,authorization,sessiontoken");
// 允许跨域请求中携带cookie response.setheader("access-control-allow-credentials", "true");
代码的上面部分是解决跨域问题的代码,而第二部分的response.setheader("access-control-allow-credentials", "true");这是允许在后端中允许携带cookie的代码。
前端代码:
$scope.login = function () { $http({ // 设置请求可以携带cookie withcredentials:true, method: 'post', params: $scope.user, url: 'http://localhost:8080/user/login' }).then(function (res) { alert(res.data.msg); }, function (res) { if (res.data.msg) { alert(res.data.msg); } else { alert('网络或设置错误'); } }) }
从以上代码,我们不难知道,在跨域请求中在前端最重要的一点在于withcredentials:true,这一语句结合后台设置的"access-control-allow-credentials", "true"就可以在跨域的ajax请求中携带cookie了。
然而,在我测试的时候发现了一些问题,当请求发出时,浏览器就报错如下
response to preflight request doesn't pass access control check: a wildcard '*' cannot be used in the 'access-control-allow-origin' header when the credentials flag is true. origin 'null' is therefore not allowed access. the credentials mode of an xmlhttprequest is controlled by the withcredentials attribute.
通过查阅相关资料,这才发现,原因是在后台解决跨域代码的response.setheader("access-control-allow-origin", "*");这部分和设置跨域携带cookie部分产生了冲突,在查阅相关资料我发现设置跨域ajax请求携带cookie的情况下,必须指定access-control-allow-origin,意思就是它的值不能为*,然而想到前后端分离的情况下前端ip是变化的,感觉又回到了原点,难道就不能用这个方法来解决ajax跨域并携带cookie这个难题?
接下来,在对我发出的ajax请求的研究中,我发现,在angularjs中,每一个请求中的origin请求头的值都为"null",这意味着什么?于是我把后台"access-control-allow-origin", "*"改成了"access-control-allow-origin", "null",接下来的事情就变得美好了,所有的ajax请求能成功的附带cookie,成功的达到了目的。
response.setheader("access-control-allow-origin", "null");
相关推荐:
nodejs中express框架的中间件及app.use和app.get方法的解析
angular1学习笔记,里面有angularjs中的view model同步过程
以上就是附带cookie如何实现ajax跨域请求的详细内容。
其它类似信息

推荐信息