cookie 跨域访问的解决方案

资料:

机制

Cookie技术是客户端的解决方案,也就是服务器发给客户端的特殊信息,而这些信息以文本文件的方式存放在客户端

对于Windows而言在 [系统盘]:\Documents and Settings[用户名]\Cookies目录中找到存储的Cookie;

客户端向服务器发送请求的时候会携带上这些cookie,存放在HTTP请求头(Request Header);

服务器响应强求的时候可以通过Set-Cookie设置Cookie

Cookie具有不可跨域名性。

协议,端口号,域名不同,视为跨域;

domain:可以访问该Cookie的域名。

path:该Cookie的使用路径。如果设置为“/”,则本域名下contextPath都可以访问该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: 'json',
    // 允许携带证书
    xhrFields: {
       withCredentials: true
    },
    // 允许跨域
    crossDomain: true,
    success: function () {},
    error: function () {}
})

服务器端设置:

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

能够成功使用带有 Cookie 的资源请求需要满足以下几个条件:

  • XMLHttpRequest 对象中指定了 withCredentials = true
  • 服务器响应头中 Access-Control-Allow-Credentials: true
  • 服务器响应头中 Access-Control-Allow-Origin 不能为 *

完整示例:

// http://abc.test.api/index.php
<?php
    header("Access-Control-Allow-Credentials: true");
    header("Access-Control-Allow-Origin: http://test.api");
    echo 2;
?>
// http://test.api/index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <button type="button" id="btn">发送</button>
    <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
    <script src="https://cdn.bootcss.com/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
    <script>
        if (!$.cookie('name')) {
            $.cookie('name', 'value', {
                domain: 'test.api'
            });
        }
        $('#btn').on('click', function () {
            $.ajax({
                xhrFields: {
                    withCredentials: true
                },
                crossDomain: true,
                type: 'post',
                url: 'http://abc.test.api/index.php',
            })
        })
    </script>
</body>
</html>
Cookies

单击发送按钮 我们可以看到


GIF.gif
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容