How to grab data from a fetch call and assign to a variable to be used in JS code?

Viewed 17

I'm trying to grab Bearer token Key from a POST call (log in to the system)

structure is as follows

    let gToken;
    let username1='username';
    let password1='password';
    let URL1='...URL';
    
    gToken=login(username1,password1,URL1);
          
    async function login(username,password,URL){
      let data;
      let token;
      const inputBody=`{"${username}","${password}"}`;
      
      const headers = "some headers"
      
      const res=await fetch(URL,{
      method:'POST',body:inputBody, headers:headers})
      data=await res.json();
      token=data.token;
      return token;
      };

      

In this scenario the gToken is returned as a promise, even though the data type of in async function of "token" is "string". My expectation would be to set the gToken to a string as well, instead of making it a promise.

Thanks for the help

0 Answers
Related