请求方法显示OPTIONS而不是POST

时间:2013-10-09 12:41:31

标签: javascript xmlhttprequest

我正在开展一个项目,我将文件上传到s3。我使用XMLHttpRequest向s3提交了一个帖子请求,并给了我一个403 Forbidden状态。当我检查我在我的firebug中提出的请求时,它显示了一个"请求方法:OPTIONS"并且它假设是一个POST请求。

以下是我的代码:

function GetXmlHttpObject () {

     var xmlHttp = null;

     try {
       // Firefox, Opera 8.0+, Safari, IE 7+
       xmlHttp = new XMLHttpRequest();
     } catch (e) {
       // Internet Explorer - old IE - prior to version 7
       try {
          xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
       } catch (e) {
          xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
       }
     }

     return xmlHttp;
    }

function uploadFile() {
    console.log(AWSAccessKeyId);
    var file = document.getElementById('file').files[0];
    var fd = new FormData();

    var key = "events/" + (new Date).getTime() + '-' + file.name;

    fd.append('key', key);
    fd.append('acl', 'public-read'); 
    fd.append('Content-Type', file.type);      
    fd.append('AWSAccessKeyId', AWSAccessKeyId);
    fd.append('policy', policyBase64)
    fd.append('signature', signature);

    fd.append("file",file);

    var xhr = GetXmlHttpObject();

    xhr.upload.addEventListener("progress", uploadProgress, false);
    xhr.addEventListener("load", uploadComplete, false);
    xhr.addEventListener("error", uploadFailed, false);
    xhr.addEventListener("abort", uploadCanceled, false);

    xhr.open('POST', 'https://'+bucket+'.s3.amazonaws.com/', true); //MUST BE LAST LINE BEFORE YOU SEND 
    xhr.setRequestHeader("Content-type","multipart/form-data");
    xhr.send(fd);
  }

我被困在这里。 T__T。

1 个答案:

答案 0 :(得分:2)

您正在触发preflighted request。浏览器正在发出OPTIONS请求,以确保它在发出POST请求之前有权(通过CORS)访问服务器。

您必须配置您的存储分区以支持带有预检请求的CORS as described in Amazon's own documentation

相关问题