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

在项目的实际开发中,我们总会遇到前后端分离的项目,在这样的项目中,跨域是第一个要解决的问题,除此之外,保存用户信息也是很重要的,然而,在后台保存用户信息通常使用的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了。

pixabayhttps://www.wode007.com/sites/73237.html wallhavenhttps://www.wode007.com/sites/73236.html

然而,在我测试的时候发现了一些问题,当请求发出时,浏览器就报错如下

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");

  

原文地址:https://www.cnblogs.com/ypppt/p/13325180.html