The Community will be undergoing maintenance from Friday February 21 - Friday, February 28 and will be "read only" during this time. To learn more, check out our Announcements blog post.
Sep 12, 2023 09:38 AM
I'm running an API POST script and I'm trying to utilize the id that is returned in the response.
This is the key piece of the script.
var postOptions = {
method: 'POST',
headers: myHeaders,
body: formdata,
redirect: 'follow'
};
let response = await remoteFetchAsync("https://xyz.com/...", postOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
I get this response. I'd like to then reference that id returned.
CONSOLE.LOG
"{"id":29644,"progress":0,"current_line":null,"status":"created","created_at":"2023-09-12T09:30:39-07:00","started_at":null,"ended_at":null,"file_url":null}"
I've tried this, but I get an undefined error.
console.log(response.result.id)
Solved! Go to Solution.
Sep 12, 2023 05:16 PM
How about this?
let response = await remoteFetchAsync("https://xyz.com/...", postOptions)
.then(response => response.json())
.catch(error => console.log('error', error));
console.log(response.id);
Sep 12, 2023 09:56 AM
If you retrieve the response as "text" you must parse the result. Alternatively, you could retrieve the response as "json" and avoid this step.
console.log(JSON.parse(result).id)
Sep 12, 2023 11:21 AM
I'm getting an error -
ReferenceError: result is not defined
Sep 12, 2023 12:50 PM
console.log(JSON.parse(response).id)
Sep 12, 2023 01:00 PM
Now error SyntaxError: "undefined" is not valid JSON
Sep 12, 2023 05:16 PM
How about this?
let response = await remoteFetchAsync("https://xyz.com/...", postOptions)
.then(response => response.json())
.catch(error => console.log('error', error));
console.log(response.id);
Sep 13, 2023 08:47 AM
Yes that's it! Nice catch.
Sep 13, 2023 09:16 AM
I tried to give you the hint the day you asked, hoping you'd lean into it and solve it independently. Often, when forced to work through the problem to resolve it, you will understand more about the underlying elements.
Sep 13, 2023 09:46 AM
Thanks. I'm pretty new to JS and I didn't catch I needed to change the reponse.text() to json() above.
Sep 13, 2023 02:52 PM
Yep - it takes about 5,000 hours to become proficient. Possibly helpful - ChatGPT. It’s not perfect but neither are we.