Skip to main content

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)

 

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)

 


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)

 


I'm getting an error - 

ReferenceError: result is not defined


I'm getting an error - 

ReferenceError: result is not defined


console.log(JSON.parse(response).id)
console.log(JSON.parse(response).id)

Now error SyntaxError: "undefined" is not valid JSON


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);

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);

Yes that's it! Nice catch.


Yes that's it! Nice catch.


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.

 


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.

 


Thanks. I'm pretty new to JS and I didn't catch I needed to change the reponse.text() to json() above. 


Thanks. I'm pretty new to JS and I didn't catch I needed to change the reponse.text() to json() above. 


Yep - it takes about 5,000 hours to become proficient. Possibly helpful - ChatGPT. It’s not perfect but neither are we.


Reply