当前位置:Gxlcms > JavaScript > 附带cookie如何实现ajax跨域请求

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

时间:2021-07-01 10:21:17 帮助过:8人阅读

本篇文章给大家带来的内容是关于附带cookie如何实现ajax跨域请求,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

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

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

  1. // 解决跨越问题
  1. 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");
  1. // 允许跨域请求中携带cookie
  2. response.setHeader("Access-Control-Allow-Credentials", "true");

代码的上面部分是解决跨域问题的代码,而第二部分的response.setHeader("Access-Control-Allow-Credentials", "true");这是允许在后端中允许携带cookie的代码。

前端代码:

  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,成功的达到了目的。

  1. response.setHeader("Access-Control-Allow-Origin", "null");

相关推荐:

nodejs中express框架的中间件及app.use和app.get方法的解析

angular1学习笔记,里面有angularjs中的view model同步过程

以上就是附带cookie如何实现ajax跨域请求的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行