我正在创建一个 XMLHttpRequest 来上传图像文件。我可以看到状态为 200,并且我的图像正在上传到我的服务。但是,当我使用下面的代码获取responseText(其中应包含图像的URL、文件名、时间戳、图像尺寸等信息)时,它会以空字符串的形式返回:
//...
const data = new FormData();
data.append('file', props);
data.append('upload_preset', uploadPreset);
data.append('api_key', apiKey);
const xhr = new XMLHttpRequest();
xhr.open('POST', cloudinaryURL, true);
const sendImage = xhr.send(data);
const imageResponse = xhr.responseText;
console.log('Response: ', imageResponse);
将其打印到控制台:
Response:
知道为什么会发生这种情况/如何解决这个问题吗?
谢谢!!
最佳答案
您正在异步模式下使用 XMLHttpRequest:
xhr.open('POST', cloudinaryURL, true);
但是您的代码是为同步模式设计的:
xhr.open('POST', cloudinaryURL, false);
在异步模式下,xhr.send()
将立即返回,而不实际处理请求。因此,当您尝试访问时,xhr.responseText
尚未填充。
关于javascript - XMLHttpRequest 的状态为 200,但 responseText 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38526994/