NodeJS and Express read JSON response in Client

I am trying to do a simple server using Express but I am having a hard time reading the info I send to the client as part of the response.

This is one of my endpoints in the server:

app.post('/click',(req, res) =>{
    res.status(200).json({'message' : 'You clicked the button!'});
}

And this is the client that make the request to the server using that endpoint:

button.addEventListener('click', function(e) {
  fetch('/click', {method: 'POST'})
    .then(function(response) {
      if(response.ok) {
        return response.json()
      }
      throw new Error('Request failed.');
    })
    .then(function(data){
      var serverInfo = JSON.parse(data)
    })
    .catch(function(error) {
      console.log(error);
    });
});

And this is not working, tried a few more things like no using JSON.parse but still not working, any idea on how I am supossed to read the server response in the client??

Upvotes: 0

Views: 1114

Answers (3)

sara khosropour
sara khosropour

Reputation: 21

You can get the JSON in the client using the following:

    button.addEventListener('click', function(e) {
      fetch('/click', {method: 'POST'})
        .then(async function(response) {
          const result = await response.json();
          console.log(result.message);
        })
    });

Upvotes: 0

Bruno Pop
Bruno Pop

Reputation: 74

Taking a quick look in the fetch you are calling the wrong endpoint.

/test/success instead of /click

Hope it will be that,

cheers!

Upvotes: 1

Siddhartha Chowdhury
Siddhartha Chowdhury

Reputation: 2732

There is a typo return response.json should be return response.json(). Try this.

Small note: dont handle error in in then block use catch block to throw error ; )

button.addEventListener('click', function(e) {
  fetch('/test/success', {method: 'POST'})
    .then(function(response) {
        return response.json()
    })
    .then(function(data){
      console.log('Do what you want => ', data)
    })
    .catch(function(error) {
      console.log(error);
    });
});

Upvotes: 0

Related Questions