Search code examples
javascriptcurlpromise

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('[email protected]: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 :

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