So I'm doing a POST request with some data I collect from an HTML form. However, I want to use the data the server sent back outside of the fetch call and this is causing me headaches.
The response is a JSON string that can contain the key 'userMessage'. I am able to print this data inside of the fetch call. I then return this data and store it in the variable response. I can log this whole object to the console but I cannot use it the same way as in the fetch call. This is my code:
email = document.forms["login"]["email"].value;
pwd = document.forms["login"]["pwd"].value;
data = JSON.stringify({'email':email, 'password': pwd});
response = fetch(
"https://companyname/path", {
method: 'POST',
headers:
{
'accept': 'application/json, text/plain, */*',
'accept-language': '[object Object]',
'app-version': '1.0.3',
'content-type': 'application/json'
},
body: data
})
.then(res => res.json())
.then(data => {
console.log('Success:', data['userMessage']); // This works
return data;
})
.catch((error) => {
console.error('Error:', error);
});
console.log(response); // This works too
alert(response['userMessage']); // This just shows an alert saying "undefined"
Why doesn't this work? How do I go around it?