Using Axios GET with authorization header in React-Native app

I am trying to use axios to request a GET with an API that requires an Authorization header.

My current code is:

 const AuthStr = 'Bearer ' + USER_TOKEN; 

where USER_TOKEN is the required access token. This string concatenation can be a problem, as if I published this as AuthStr = 'Bearer 41839y750138-391' , the next GET request will work and returns the data that I followed.

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

I also tried to set this as a global header without success.

+6
source share
2 answers

For someone else who comes across this post and might find it useful ... There is nothing wrong with my code. I made a mistake when requesting an access code of type client_credentials instead of a password access code (#facepalms). FYI I use urlencoded message, therefore, use querystring .. So, for those who can look for some sample code .. here is my full request

Many 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); }); 
+10
source

Actually this problem occurs in xcode, does not support HTTP request in localy.

you can add this code to the .plist file

 <key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <true/> </dic> 
-one
source

Source: https://habr.com/ru/post/1013857/


All Articles