Ajax / Jquery请求不发送cookie

时间:2016-04-05 15:27:15

标签: jquery ajax cross-domain jquery-file-upload blueimp

我使用blueimp/jQuery-File-Upload脚本进行跨域(子域)上传。主页面是www.example.com,我将文件上传到st2.example.com。

一切正常,但问题是我需要发送每个ajax请求的cookie,并且出于某种原因,这是不可能的。该脚本的文档说:

  

如果您需要发送cookie(例如用于身份验证),请设置   withCredentials $ .ajax()设置为fileupload小部件选项:

$('#fileupload').fileupload('option', {
xhrFields: {
withCredentials: true
}
});

这对我不起作用。我试着添加一行

withCredentials: true

在三个不同的地方:

  • 到$('#fileupload')。fileupload({
  • 到$('#fileupload')。fileupload('option',{
  • 到$ .ajax({

前2个根本不起作用。第三个仅适用于 HEAD 请求。 HEAD 请求发送Cookie,但 OPTIONS POST 不发送。我在Firefox和Chrome浏览器控制台中检查了这个。

我的问题是:OPTIONS和POST请求不发送任何cookie的问题在哪里?

以下是我的脚本。这个例子在我测试过的所有3个地方都包含“withCredentials:true”。

    <script>
    var defaultthumbnail = '<img class="thum5" src="/upload.png">';
    $(function () {
    var formData = $('#fileupload').serializeArray();
    'use strict';
    $('#fileupload').fileupload({
xhrFields: {withCredentials: true},
    url:'//st2.example.com/',
    });

    $('#fileupload').fileupload('option', {
    acceptFileTypes: /(\.|\/)(jpe?g)$/i,
    autoUpload:true,
    maxNumberOfFiles:20,
    maxFileSize:4000000,

  xhrFields: {withCredentials: true},

    disableImageResize: /Android(?!.*Chrome)|Opera/
    .test(window.navigator.userAgent)
    });

    if ($.support.cors) {
    $.ajax({
xhrFields: {withCredentials: true},
    url: $('#fileupload').fileupload('option', 'url'),
    type: 'HEAD'
    }).fail(function () {
    $('<div class="error"/>')
    .text('Server is not available')
    .appendTo('#fileupload');
    });
    } 
    });
    </script>

st2.example.com上的文件包含:

header('Access-Control-Allow-Origin: http://www.example.com');
header("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Methods: HEAD, GET, PUT, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Content-Range, Content-Disposition, Content-Description');

1 个答案:

答案 0 :(得分:1)

问题是Cloudflare。首先,浏览器向服务器发送OPTIONS请求,以查看是否可以上传文件。 OPTIONS请求总是没有cookie,这就是Cloudflare发出另一个验证码挑战页面而不是将请求转发给服务器的原因。