Reputation: 6363
I'm making an XMLHttpRequest to upload an image file. I can see that it's a 200 status and my image is uploading onto my service. However, when I use the code below to get the responseText (which should include information such as: URL for my image, filename, timestamps, image dimensions, etc.), it comes back as an empty string:
//...
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);
Prints this to the console:
Response:
Any idea why this is happening / how to resolve this issue?
Thanks!!
Upvotes: 0
Views: 3685
Reputation: 6110
You are using XMLHttpRequest in asynchronous mode:
xhr.open('POST', cloudinaryURL, true);
But your code is designed for synchronous mode:
xhr.open('POST', cloudinaryURL, false);
In asynchronous mode, xhr.send()
will return immediately without actually processing the request. So, xhr.responseText
hasn't been populated yet when you try to access it.
Upvotes: 4