我正在制作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:
知道为什么会这样做/如何解决这个问题?
谢谢!
答案 0 :(得分:3)
您正在异步模式下使用XMLHttpRequest:
xhr.open('POST', cloudinaryURL, true);
但您的代码是为同步模式设计的:
xhr.open('POST', cloudinaryURL, false);
在异步模式下,xhr.send()
将立即返回,而不会实际处理请求。因此,当您尝试访问时,xhr.responseText
尚未填充。