CORS、Ajax和Cookie

原创
2016/09/11 17:25
阅读数 292

CORS是ajax跨域请求的一个解决方案,详细见:

浏览器同源政策及其规避方法
跨域资源共享 CORS 详解

ajax可以设置请求头,和get响应头

jQuery and AJAX response header
How can I add a custom HTTP header to ajax request with js or jQuery?

先感受一下,编写index.html:

<!DOCTYPE html>
<html>
<head>
    <title>test</title>
</head>
<body>

    <button id="test">click</button>


    <script src="//cdn.bootcss.com/jquery/3.1.0/jquery.min.js"></script>
    <script>
    $('#test').on('click', function(){
        console.log('click me');
        var url = 'https://api.github.com/users/octocat/gists';

        var geturl = $.ajax({
            type: "GET",
            url: 'https://api.github.com/users/octocat/gists',
            success: function (data) {
                console.log('header:\n', geturl.getAllResponseHeaders());
                console.log('data:\n', data);
            }
        });

    });
    </script>

</body>
</html>

npm安装http-server模块,在index.html目录下执行http-server命令,浏览器打开 http://127.0.0.1:8080/,点击按钮,看下console的输出:

这个响应头是被过滤过的,另外原则上是无法获取Set-cookie的值。 见How to get a cookie from an AJAX response?

其他

jQuery如何获取响应头: http://api.jquery.com/jQuery.ajax/#jqXHR

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
3 收藏
0
分享
返回顶部
顶部