Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Empty promise object value from POST curl in JavaScript

I have the following Curl code in JavaScript :

function login() {
    var obj;
    const outputElement = document.getElementById('output');

  return fetch('http://localhost:3000/api-keys', {
  method: 'POST',
  headers: {
    'Authorization': 'Basic ' + btoa('john@gmail.com:123456'),
    "content-type": "application/json"
  }
}).then(function(response) {
    obj = response.json();
    }).then(() => {
        outputElement.textContent = obj;
    })
    
}

but the element with id = output prints this :

[object Promise]

And if I print it in the console, with the same code as before but adding this instead :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

...
.then(function(response) {
        obj = response.json();
        }).then(() => {
           console.log(obj);
        })
...

I get this :

enter image description here

And when I expand the arrow to the left of PromiseResult, I get this :

user_id: 2
user_name: john
created_at: "2024-01-04T04:01:03.855Z"
address: "Some address"

Which is what I want, but I cannot print it or store it, it’s only available in the console.

>Solution :

The issue is response.json() returns a(another) Promise so you will require another then to handle the resolved data. Something like:

function login() {
    // ...rest

    return fetch(
    // ...rest of your code
    }).then(function(response) {
        return response.json(); // return the promise
    }).then(function(data) { // <-- Notice this another then to handle data
        console.log(data); // log the data to the console
        outputElement.textContent = JSON.stringify(data); // display the data in the output element
    });
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading