I am currently facing an issue when trying to utilize the JSON data returned from a fetch on the backend without causing any errors.
The fetch operation runs smoothly and returns a JSON response if I exclude the problematic line below:
fetch("https://dash.stannp.com/api/v1/postcards/create?api_key=" + secret + "&", requestOptions)
.then(response => response.text())
.then(result => {
let item = result
console.log("item: " + item)
//this line causes an error
console.log("pdf: " + item.data.pdf)
return (item)
})
The console.log("item: " + item)
line displays the following:
item: {
"success":true,
"data": {
"pdf": "https:\/\/dash.stannp.com\/api\/v1\/storage\/get\/rum\/1588348478\/pdf-samples\/7476-cda247f3-c634-43bf-8d03-731908549fb1-A6-4add27e8-b08f-4495-846b-7d904e.pdf",
"id":"0",
"created":"2020-05-01T15:54:38+00:00",
"format":"A6",
"cost":"0.59"
}
}
After this, the
console.log("pdf: " + item.data.pdf)
line, which immediately follows the first one, triggers an error.
I'm unsure of what I'm doing wrong and how I can properly use the pdf link. Any help would be appreciated.
In case it's relevant, I suspect that there might be some issues with promises as the return statement executes before the fetch operation is completed.
Here is the complete code in case it aids in understanding the problem:
export function previewStannpSingleCard2(card) {
return getSecret("stannp_API")
.then((secret) => {
var myHeaders = {
"Content-Type": "application/json"
}
var myBody = JSON.stringify({
// data here...
})
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: myBody,
redirect: 'follow'
};
fetch("https://dash.stannp.com/api/v1/postcards/create?api_key=" + secret + "&", requestOptions)
.then(response => response.text())
.then(result => {
let item = result
console.log("item: " + item)
//console.log("pdf: " + item.data.pdf)
return (item)
})
.catch(error => console.log('error', error));
})
}
Thank you for your assistance.