【问题标题】:Javascript CORS upload always finishing with an error eventJavascript CORS 上传总是以错误事件结束
【发布时间】:2013-05-01 03:57:48
【问题描述】:

我需要按照CORS 规范和javascript 将文件上传到服务器。

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

如果我查看目标,XMLHttpRequestreadyState=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); }

【问题讨论】:

    标签: javascript ajax xmlhttprequest cors


    【解决方案1】:

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

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

    【讨论】:

    • 这对我来说似乎很奇怪,因为据我所知,服务器负责返回这个“Access-Control-Allow-Origin”标头。我认为您实际上在服务器端更改了其他内容
    猜你喜欢
    • 2014-10-24
    • 2018-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多