在前后端分离的项目中,ajax跨域请求怎样附带cookie

在项目的实际开发中,我们总会遇到前后端分离的项目,在这样的项目中,跨域是第一个要解决的问题,除此之外,保存用户信息也是很重要的,然而,在后台保存用户信息通常使用的session和cookie结合的方法,而在前端的实际情况中,跨域产生的ajax是无法携带cookie信息的,这样导致了session和cookie的用户信息储存模式受到影响,该怎样去解决这样一个问题呢,通过查阅资料,我这里以angularJS的$http中的ajax请求来举例子。

首先,在后台我使用的servlet的filter拦截所有的请求,并设置请求头:

[java]  view plain  copy
  1. <span style="white-space:pre;"> </span>// 解决跨越问题  
[java]  view plain  copy
  1. <span style="white-space:pre;"> </span>response.setHeader("Access-Control-Allow-Origin""*");  
  2.         response.setHeader("Access-Control-Allow-Methods""*");  
  3.         response.setHeader("Access-Control-Max-Age""3600");  
  4.         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");  
  5.           
[java]  view plain  copy
  1. <span style="white-space:pre;"> </span>// 允许跨域请求中携带cookie  
  2.         response.setHeader("Access-Control-Allow-Credentials""true");  
代码的上面部分是解决跨域问题的代码,而第二部分的response.setHeader("Access-Control-Allow-Credentials", "true");这是允许在后端中允许携带cookie的代码。

前端代码:

[javascript]  view plain  copy
  1. $scope.login = function () {  
  2.                 $http({  
  3.                     // 设置请求可以携带cookie  
  4.                     withCredentials:true,  
  5.                     method: 'post',  
  6.                     params: $scope.user,  
  7.                     url: 'http://localhost:8080/user/login'  
  8.                 }).then(function (res) {  
  9.                     alert(res.data.msg);  
  10.                 }, function (res) {  
  11.                     if (res.data.msg) {  
  12.                         alert(res.data.msg);  
  13.                     } else {  
  14.                         alert('网络或设置错误');  
  15.                     }  
  16.                 })  
  17.             }  
从以上代码,我们不难知道,在跨域请求中在前端最重要的一点在于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,成功的达到了目的。

[java]  view plain  copy
  1. response.setHeader("Access-Control-Allow-Origin""null");  

猜你喜欢

转载自blog.csdn.net/myth_g/article/details/79706908