我有一个简单的代码,可以将文件从 https://app.myserver:4202
发送到服务器 https://myserver/backend/upload.php
:
//script executed on`https://app.myserver:4202`
var xhr = new XMLHttpRequest();
xhr.open("POST", "https://myserver.com/backend/upload.php");
xhr.withCredentials = true;
xhr.send(fd); //fd is formdata from file input
是的,它成功地发送了带有 cookie 的文件,因此我可以在我的 upload.php 脚本中执行用户身份验证。现在,我也想显示进度条,所以我将代码更改为:
var xhr = new XMLHttpRequest();
xhr.open("POST", "https://myserver.com/backend/upload.php");
xhr.withCredentials = true;
xhr.upload.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
console.log("add upload event-listener" + evt.loaded + "/" + evt.total);
}
}, true);
xhr.send(fd);
哇,一切都乱套了!我们有一个 CORS 问题。请注意,我只添加了一个进度跟踪器。
Access to XMLHttpRequest at 'https://myserver/backend/upload.php' from origin 'https://myserver:4202' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
我非常小心地正确设置了 CORS,所以这是与 CORS 相关的 myserver
响应 header
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: origin, x-requested-with, content-type
Access-Control-Allow-Methods: DELETE, HEAD, GET, OPTIONS, POST, PUT
Access-Control-Allow-Origin: https://app.myserver.com:4202
Access-Control-Max-Age: 86400
如果不需要进度信息,它们运行良好,但在跟踪时失败。
那么告诉我,我在这里错过了什么?
最佳答案
We have a CORS problem. Notice that I only added a progress tracker.
此行为是 defined in the spec :
Registering one or more event listeners on an XMLHttpRequestUpload object will result in a CORS-preflight request. (That is because registering an event listener causes the upload listener flag to be set, which in turn causes the use-CORS-preflight flag to be set.)
I took great care to setup CORS correctly so this are myserver response headers that are relevant to CORS
仔细阅读错误信息:
Access to XMLHttpRequest at 'https://myserver/backend/upload.php' from origin 'https://myserver:4202' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
因此您设置的 HTTP 响应 header 并不真正相关。
浏览器正在发出 OPTIONS 请求以请求发出 POST 请求的权限,并且服务器正在响应 200 OK
之外的内容。
可能它正在发送 405 Method Not Allowed
。检查开发人员工具的网络选项卡,准确了解 HTTP 响应状态,然后相应地调整服务器。
关于javascript - 如果跟踪进度,则 XMLHttpRequest 无法发送 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54215912/