Using Axios GET with Authorization Header in React-Native App

前端 未结 2 1618
时光取名叫无心
时光取名叫无心 2020-12-13 18:27

I\'m trying to use axios for a GET request with an API which requires an Authorization header.

My current code:



        
相关标签:
2条回答
  • 2020-12-13 18:32

    Could not get this to work until I put Authorization in single quotes:

    axios.get(URL, { headers: { 'Authorization': AuthStr } })

    0 讨论(0)
  • 2020-12-13 18:45

    For anyone else that comes across this post and might find it useful... There is actually nothing wrong with my code. I made the mistake of requesting client_credentials type access code instead of password access code (#facepalms). FYI I am using urlencoded post hence the use of querystring.. So for those that may be looking for some example code.. here is my full request

    Big thanks to @swapnil for trying to help me debug this.

       const data = {
          grant_type: USER_GRANT_TYPE,
          client_id: CLIENT_ID,
          client_secret: CLIENT_SECRET,
          scope: SCOPE_INT,
          username: DEMO_EMAIL,
          password: DEMO_PASSWORD
        };
    
    
    
      axios.post(TOKEN_URL, Querystring.stringify(data))   
       .then(response => {
          console.log(response.data);
          USER_TOKEN = response.data.access_token;
          console.log('userresponse ' + response.data.access_token); 
        })   
       .catch((error) => {
          console.log('error ' + error);   
       });
    
    
    
    const AuthStr = 'Bearer '.concat(USER_TOKEN); 
    axios.get(URL, { headers: { Authorization: AuthStr } })
     .then(response => {
         // If request is good...
         console.log(response.data);
      })
     .catch((error) => {
         console.log('error ' + error);
      });
    
    0 讨论(0)
提交回复
热议问题