我需要使用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); }
答案 0 :(得分:0)
问题在于,虽然我将服务器设置为在OPTIONS
请求中发回相应的标头,但我没有在实际Access-Control-Allow-Origin
中发送POST
。
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');