Getting response data from fetch request

Hi guys,

I am building a small API to be consumed by my Fuse application. I can communicate with my API (GET/POST works fine), however I don’t know how to show the messages that my API sends back through the response.

A successful response looks like this:

{
  "success": true,
  "message": "The user was successfully created.",
  "api_token": "W6UlkYK4QzK1C5mZ2HpzyZEGmuXo19JnqHKEm6u7bMQVORfe6IvSjW4LNnbZ"
}

While an unsuccessful response looks like this:

{
  "name": [
    "The name field is required."
  ],
  "email": [
    "The email has already been taken."
  ],
  "password": [
    "The password field is required."
  ]
}

I tried a number of different things in my code as you can see below:

saveUser: function() {
  var payload = {name: 'Something', email: 'teestasdaassysasasa@test.dk', password: 'somepw'};

  fetch('https://stifling-mandrill-0773.vagrantshare.com/api/v1/users/register', {
  method: 'POST',
  headers: {
  "Content-type": "application/json",
  "Accept": "application/json"
  },
  body: JSON.stringify(payload)

  }).then(function(response) {
  //console.log("1");
  console.log(response.json());
  console.log(response);
  //return response.json(); 

  var errors = JSON.stringify(response.responseJSON);

  if (response.status === 422) {
  errors.forEach(function(error) {
  console.log(error);
  });
  }

  });

}

I get this from the above in my console:

    Fuse.Scripting.V8.Object

But how do I dive into these objects?

I am still very new to this stuff, but hope someone could help me in the right direction here :slight_smile:

Hi

You need to do response.json().then(function(json) { console.log(json); })

Google for fetch api for more info

Hi Anders,

I think I figured it out by looking more closely into their documentation, just couldn’t wrap my head around why there was a return statement in the first promise I guess :).

Thanks for your help, and really great job on Fuse so far, im excited to see what will happen in the future!