Javascript CORS上传总是以错误事件结束

时间:2013-05-07 08:52:10

标签: javascript ajax xmlhttprequest cors

我需要使用CORS javascript规范将文件上传到服务器。

互联网上有很多例子,事实上一切正常(文件已上传),但上次触发的事件是错误的。

如果我查看目标,XMLHttpRequest会以readyState=4为准。根据规范,这是

DONE: The data transfer has been completed or something went wrong during the transfer (e.g. infinite redirects).

source http://www.w3.org/TR/XMLHttpRequest/#dom-xmlhttprequest-readystate

status始终为0但文件确实上传,进度正常,服务器返回201 CREATED

一段代码:

var fd = new FormData(document.getElementById('viForm'));
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", submitAddress);
xhr.setRequestHeader('X-Auth-Token', token);
xhr.send(fd);


function uploadFailed(e) { console.log(e); }

1 个答案:

答案 0 :(得分:0)

问题在于,虽然我将服务器设置为在OPTIONS请求中发回相应的标头,但我没有在实际Access-Control-Allow-Origin中发送POST

xhr.setRequestHeader('Access-Control-Allow-Origin', '*');