Home > OS >  Attempting to log JSON response from REST API in JavaScript using Fetch
Attempting to log JSON response from REST API in JavaScript using Fetch

Time:10-26

I have a small script that I have put together. The script does the following:

  • Defines several variables within an array

  • Passes those values to an API

  • API should return an access token

     const fetch = require('node-fetch');
     var orgInfo = {
                 client_id: 'idgoeshere', 
                 client_secret: 'secretgoeshere', 
                 username: 'usernamegoeshere', 
                 password: 'passwordgoeshere', 
                 grant_type: 'granttypegoeshere'
             };
    
     fetch('https://urlgoeshere', {
         method: "GET",
         body: JSON.stringify(orgInfo),
         headers: {
         "Content-Type": "application/json"
     },
    
     credentials: "include"
    
     }).then(function(response) {
    
     response.access_token
     response.bearer
     response.expires_in
     response.scope
    
     return repsonse.text()
    
     }, function(error) {
         error.message
     })
    
     console.log(orgInfo);
     console.log(response.access_token);
    

When I log orgInfo, I do get the following output:

{ client_id: 'idgoeshere',
  client_secret: 'secretgoeshere',
  username: 'usernamegoeshere',
  password: 'passwordgoeshere',
  grant_type: 'granttypegoeshere' }

When I try to log response.access_token, I get a ReferenceError: response is not defined

My questions are:

  • Does response need to be defined? Obviously, Im being yelled at because it isnt.
  • Is there a way to see if I am getting anything back from the API automagically?

Im not looking for someone to spoon-feed me an answer, rather I am simply looking for a push in the right direction. That would be stellar.

Thanks

UPDATE

So this is what I have:

const fetch = require('node-fetch');

const orgInfo = {
client_id: ' ', 
client_secret: ' ', 
username: ' ', 
password: ' ', 
grant_type: ' '
};

(async() => {

const response =  await fetch('https:// ', {
    method: "GET",
    body: JSON.stringify(orgInfo),
    headers: {
        "Content-Type": "application/json"
    }
});

const data = await response.json();
console.log(data)
})

This returns no errors when running but also doesnt return the value of data

CodePudding user response:

const fetch = require('node-fetch');
var orgInfo = {
             client_id: 'idgoeshere', 
             client_secret: 'secretgoeshere', 
             username: 'usernamegoeshere', 
             password: 'passwordgoeshere', 
             grant_type: 'granttypegoeshere'
};

fetch('https://urlgoeshere', {
     method: "GET",
     body: JSON.stringify(orgInfo),
     headers: {
          "Content-Type": "application/json"
     },
     credentials: "include"
}).then(function(response) {

     response.access_token
     response.bearer
     response.expires_in
     response.scope

     console.log(response.access_token);

     return repsonse.text()

 }, function(error) {
     error.message
 })

 console.log(orgInfo);

response ins scoped inside the function called by the then method so it is accessible only inside of this function

CodePudding user response:

fetch returns a Promise object.

A Promise represents the eventual completion (or failure) of an asynchronous operation and its resulting value. That means response.access_token is only guaranteed to have a value (if any) inside the .then block as response is only evaluated when the promise has been fulfilled.

The reason you get nothing in the console is that you are trying to access access_token when it is not guaranteed to have a value (and thus console.log outputs nothing - there is nothing to output).


To fix this, you need to access the access_token property when you are guaranteed to have a response.

That is after the promise has been fulfilled, so either:

  1. Move the console.log(response.access_token); inside the .then clause

Or a cleaner, more modern solution would be to:

  1. Use await (equivalent syntactical sugar)

N.B. The Response object is the representation of the entire HTTP response.

You're using response.text() which will parse the response body as a string, not a JS object with properties.

I'm assuming you want to parse the body content from the Response object as JSON into a JS object. In that case, use the json() method which will then return a 2nd promise resolving with the JavaScript object obtained from the parsing of the response body.

The result should have the access_token property you want (considering the API endpoint returns it).

This should work:

const response =  await fetch('https://urlgoeshere', {
     method: "GET",
     body: JSON.stringify(orgInfo),
     headers: {
     "Content-Type": "application/json"
 };

const data = await response.json();

console.log(data.access_token);
console.log(data.bearer);
console.log(data.expires_in);
console.log(data.scope);
...

CodePudding user response:

return repsonse.text() should be ----> return response.text()

According to Fetch Documentation

  • "The Response interface of the Fetch API represents the response to a request. You can create a new Response object using the Response.Response() constructor, but you are more likely to encounter a Response object being returned as the result of another API operation—for example, a service worker Fetchevent.respondWith, or a simple fetch().

For your question "Is there a way to see if I am getting anything back from the API automagically?"

  • You can try using console.log(response.status); which will give you the status code of your request. These codes can be found HERE. And an example of this being used HERE.

  • I highly recommend trying to use Postman or Thunder-client if you can which simplifies all of this and gives you everything you need to know about the response. It is very useful to test API calls and know exactly what is happening. You also have the ability to see your call written in other languages automatically.

  • Related