XMLHttpRequest具有200状态,但responseText为空

时间:2016-07-22 12:53:37

标签: javascript xmlhttprequest

我正在制作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:  

知道为什么会这样做/如何解决这个问题?

谢谢!

1 个答案:

答案 0 :(得分:3)

您正在异步模式下使用XMLHttpRequest:

xhr.open('POST', cloudinaryURL, true);

但您的代码是为同步模式设计的:

xhr.open('POST', cloudinaryURL, false);

在异步模式下,xhr.send()将立即返回,而不会实际处理请求。因此,当您尝试访问时,xhr.responseText尚未填充。