【发布时间】:2016-07-25 15:35:42
【问题描述】:
我使用blueimp/jQuery-File-Upload 脚本进行跨域(子域)上传。主页是 www.example.com,我将文件上传到 st2.example.com。
一切正常,但问题是我需要在每个 ajax 请求中发送 cookie,并且由于某种原因这是不可能的。该脚本的文档说:
如果您需要发送 cookie(例如用于身份验证),请设置 withCredentials $.ajax() 设置为文件上传小部件选项:
$('#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');
【问题讨论】:
标签: jquery ajax cross-domain jquery-file-upload blueimp