Using Axios GET with Authorization Header in React-Native App

React NativeOauth 2.0Http HeadersFetchAxios

React Native Problem Overview


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

My current code:

const AuthStr = 'Bearer ' + USER_TOKEN;

where USER_TOKEN is the access token needed. This string concatenation may be the issue as if I post this as AuthStr = 'Bearer 41839y750138-391', the following GET request works and returns the data I'm after.

axios.get(URL, { 'headers': { 'Authorization': AuthStr } })
  .then((response => {
    console.log(response.data);
  })
  .catch((error) => {
    console.log(error);
  });

I also tried setting this as a global header with no success.

React Native Solutions


Solution 1 - React Native

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);
  });

Solution 2 - React Native

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlly HaireView Question on Stackoverflow
Solution 1 - React NativeAlly HaireView Answer on Stackoverflow
Solution 2 - React NativeMichael WingView Answer on Stackoverflow