On my website, I use a fetch POST request on an azure function to store some data. If the function receives all the data, then context.res.satus
is set to 200, and otherwise set to 400, and context.res.body
is set to an acknowledgement message depending on how much of the data is received:
var returnMessage = mail ? "User entry successfully added to the database" : "Please enter a valid email";
returnMessage = phone ? returnMessage : "Please enter a valid phone number";
returnMessage = lName ? returnMessage : "Please provide your last name";
returnMessage = fName ? returnMessage : "Please procide your first name";
returnMessage = partKey ? returnMessage : "Something went wrong while generating a partition key";
context.res = {
status: (partKey && fName && lName && phone && mail) ? 200 : 400,
body: returnMessage
};
So, I call fetch('URL',someStuff).then((res) => processResponse(res))
in my code, and res
is always returned absolutely fine and passed to processResponse
, which looks like this:
function processResponse(response) {
if (response.status === 200) {
var test = JSON.stringify(response.body);
document.getElementById("output").innerHTML = `<div class="alert alert-success" role="alert">${test}</div>`;
}
}
If the function receives all the data, the div element 'output' is updated, and if it doesn't then it isn't, so the comparison of response.status
to the value of 200 clearly works. the variable test
I originally thought would work if set to response.body
, but this didn't work, and instead the variable test
would be set to the word 'Object'. I know very little about JSON but apparently we can use JSON.stringify()
to convert Objects to Strings, hence why test
is now JSON.stringify(response.body)
, however this just makes the value of test
equal to a set of empty square brackets. In the tutorial I am working from, they say to use response.json()
, like so:
function processResponse(response) {
if (response.status === 200) {
response.json()
.then(function(data) {
document.getElementById("output").innerHTML = `<div class="alert alert-success" role="alert">${data.message}</div>`;
})
.catch(function(){
document.getElementById("output").innerHTML = `<div class="alert alert-success" role="alert">"Caught"</div>`;
});
}
}
However every time I try response.json()
, it fails and only the .catch()
part runs. What is happening and how do I access the string stored in response.body
?