温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何解决Ajax跨域访问Cookie丢失问题

发布时间:2021-06-29 15:22:27 阅读:159 作者:小新 栏目:web开发
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

这篇文章将为大家详细讲解有关如何解决Ajax跨域访问Cookie丢失问题,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

1.ajax跨域访问,cookie丢失

首先创建两个测试域名

a.fdipzone.com 作为客户端域名

b.fdipzone.com 作为服务端域名

测试代码

setcookie.PHP 用于设置服务端cookie

<?php
setcookie('data'time(), time()+3600);
?>

server.php 用于被客户端请求

<?php
$name isset($_POST['name'])? $_POST['name'] : '';
$ret array(
 'success' => true,
 'name' => $name,
 'cookie' => isset($_COOKIE['data'])? $_COOKIE['data'] : ''
);
// 指定允许其他域名访问
header('Access-Control-Allow-Origin:http://a.fdipzone.com');
// 响应类型
header('Access-Control-Allow-Methods:POST'); 
// 响应头设置
header('Access-Control-Allow-Headers:x-requested-with,content-type');
header('content-type:application/json');
echo json_encode($ret);
?>

test.html 客户端请求页面

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
 <meta http-equiv="content-type" content="text/html;charset=utf-8">
 <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
 <title> ajax 跨域访问cookie丢失的解决方法 </title>
 </head>
 <body>
 <script type="text/javascript">
 $(function(){
  $.ajax({
   url'http://b.fdipzone.com/server.php'// 跨域
   dataType'json',
   type'post',
   data: {'name':'fdipzone'},
   success:function(ret){
    if(ret['success']==true){
     alert('cookie:' + ret['cookie']);
    }
   }
  });
 })
 </script>
 </body>
</html>

首先先执行http://b.fdipzone.com/setcookie.php, 创建服务端cookie。

然后执行http://a.fdipzone.com/test.html

输出

{"success":true,"name":"fdipzone","cookie":""}

获取cookie失败。

2.解决方法

客户端

请求时将withCredentials属性设置为true

使可以指定某个请求应该发送凭据。如果服务器接收带凭据的请求,会用下面的HTTP头部来响应。

服务端

设置header

header("Access-Control-Allow-Credentials:true");

允许请求带有验证信息

test.html 修改如下

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
 <meta http-equiv="content-type" content="text/html;charset=utf-8">
 <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
 <title> ajax 跨域访问cookie丢失的解决方法 </title>
 </head>
 <body>
 <script type="text/javascript">
 $(function(){
  $.ajax({
   url'http://b.fdipzone.com/server.php'// 跨域
   xhrFields:{withCredentialstrue}, // 发送凭据
   dataType'json',
   type'post',
   data: {'name':'fdipzone'},
   success:function(ret){
    if(ret['success']==true){
     alert('cookie:' + ret['cookie']);
    }
   }
  });
 })
 </script>
 </body>
</html>

server.php 修改如下

<?php
$name isset($_POST['name'])? $_POST['name'] : '';
$ret array(
 'success' => true,
 'name' => $name,
 'cookie' => isset($_COOKIE['data'])? $_COOKIE['data'] : ''
);
// 指定允许其他域名访问
header('Access-Control-Allow-Origin:http://a.fdipzone.com');
// 响应类型
header('Access-Control-Allow-Methods:POST'); 
// 响应头设置
header('Access-Control-Allow-Headers:x-requested-with,content-type');
// 是否允许请求带有验证信息
header('Access-Control-Allow-Credentials:true');
header('content-type:application/json');
echo json_encode($ret);
?>

按之前步骤执行,请求返回

{"success":true,"name":"fdipzone","cookie":"1484558863"}

获取cookie成功

3.注意事项

1.如果客户端设置了withCredentials属性设置为true,而服务端没有设置Access-Control-Allow-Credentials:true,请求时会返回错误。

XMLHttpRequest cannot load http://b.fdipzone.com/server.php. Credentials flag is 'true', but the 'Access-Control-Allow-Credentials' header is ''. It must be 'true' to allow credentials. Origin 'http://a.fdipzone.com' is therefore not allowed access.

2.服务端header设置Access-Control-Allow-Credentials:true后,Access-Control-Allow-Origin不可以设为*,必须设置为一个域名,否则回返回错误。

XMLHttpRequest cannot load http://b.fdipzone.com/server.php. A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' heade

下面看下Ajax跨域请求COOKIE无法带上的解决办法

原生ajax请求方式:

var xhr = new XMLHttpRequest(); 
xhr.open("POST""http://xxxx.com/demo/b/index.php"true); 
xhr.withCredentials = true//支持跨域发送cookies
xhr.send();

jquery的ajax的post方法请求:

 $.ajax({
    type"POST",
    url"http://xxx.com/api/test",
    dataType'jsonp',
    xhrFields: {
      withCredentialstrue
    },
   crossDomaintrue,
   success:function(){
  },
   error:function(){
 }
})

服务器端设置:

header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Origin: http://www.xxx.com");

关于“如何解决Ajax跨域访问Cookie丢失问题”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

原文链接:https://www.jb51.net/article/104440.htm

AI

开发者交流群×