skip to Main Content

I would like to ask if someone can give me explanation or check of javascript code for this case:

  1. I call my API to get access token and I have it.
  2. Next, I want to use this token to make another calls to the API for specific data.
  3. I need to get fields from API like: description, color, dimensions.

Example to verify below

function Get() {
  var myHeaders = new Headers();
  myHeaders.append("Content-Type", "application/json");
  myHeaders.append("Authorization", `Bearer ${token.then((data)=>{data.access_token})}`);
  var requestOptions = {
    method: 'GET',
    headers: myHeaders,
    redirect: 'follow'
  };

};
const first = fetch("https://XXXXX", requestOptions)
const second = first.then(response => response.json())
return second;
}
console.log('Show data', data)

Result is – illegal return statement. But I think I missed part of code to select fields from API.

3

Answers


  1. function Get() {
      var myHeaders = new Headers();
      myHeaders.append("Content-Type", "application/json");
      myHeaders.append("Authorization", `Bearer ${token.then((data) => { data.access_token })}`);
      var requestOptions = {
        method: 'GET',
        headers: myHeaders,
        redirect: 'follow'
      };
    
      const first = fetch("https://XXXXX", requestOptions)
      const second = first.then(response => response.json())
      return second;
    }
    let data = Get()
    console.log('Show data', data)
    

    maybe you put the curly braces wrong so the fetch can’t use the correct header, please try this code

    also make sure you already store or get the token first so you can attach it to Bearer token

    Login or Signup to reply.
  2. I call my API to get access token and I have it.

    async function token(username, password) {
      const response = await fetch("https://stackexchange.com/", {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ username, password })
      });
    
      const access = await response.json();
    
      return access.access_token;
    }
    

    Next, I want to use this token to make another calls to the API for specific data.

    async function fields(access_token) {
        const requestOptions = {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${access_token}`
          }
        };
        
      const response = await fetch("https://stackoverflow.com/", requestOptions);
    
      const { description, color, dimensions } = await response.json();
    
      return { description, color, dimensions };
    }
    

    I need to get fields from API like: description, color, dimensions.

    const access = await token('Luq', 'Gorski')
    const result = await fields(access);
    
    console.log('Description:', result.description, 'Color:', result.color, 'Dimensions:', result.dimensions);
    
    Login or Signup to reply.
  3. It would be better if the "token" function is provided. I assume "token" is a function to get the token from a storage.
    The lines

    const second = first.then(response => response.json())
    

    and

    token.then((data)=>{data.access_token}
    

    are not getting the response json object but just the promise.

    It will be much easier to read if we modify the code in async/await function

    
    async function token(){
    return {access_token: "abcd"}
    }
    
    //we define a function as async
    async function Get() {
     const myHeaders = new Headers();
     
     const tokenVar = await token();
     myHeaders.append("Content-Type", "application/json");
     myHeaders.append("Authorization", `Bearer ${tokenVar.access_token}`);
     const requestOptions = {
     method: 'GET',
     headers: myHeaders,
     redirect: 'follow'
     };
     //fetch the url
     const response = await fetch("https://XXXXX", requestOptions)
     //get the response and put it in json format
     const responseJson = await response.json();
     return responseJson;
    };
    
    //call the function Get() to test
    console.log('Show data', await Get())
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search