Using Axios GET with Authorization Header in React-Native App - react-native

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.

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

Could not get this to work until I put Authorization in single quotes:
axios.get(URL, { headers: { 'Authorization': AuthStr } })

Related

Axios formData with image is sending empty array

I have a put method to my profile route in the backend, I need a token authentication so in order to be authorized I have to pass the token through a header, I get an error because for some reason it's sending an empty formData when I log the request in my backend.
I tested the backend with postman and everything works as intended so it's not a backend issue, it's totally something wrong in the request I'm doing from the frontend, but I don't know how to handle this, any clue?
profile_update() {
let params = {
email: this.profile.email,
password: this.profile.password,
coin: this.profile.coin,
phone_country: this.profile.phone_country,
phone_area: this.profile.area_code,
phone_number: this.profile.number,
first_name: this.profile.first_name,
last_name: this.profile.last_name,
date_of_birth: this.profile.date_of_birth,
gender: this.profile.gender,
city_id: this.profile.city,
wants_to_change_password: this.profile.wants_to_change_password,
state_id: this.profile.state,
city_id: this.profile.city
}
let headers = {
'Authorization': 'Bearer' + this.token
}
let formData = new FormData();
formData.append('profile-picture', this.profile.profile_picture)
formData.append('data', params)
formData.append('headers', headers)
formData.append('_method', 'PUT')
axios.put(`http://127.0.0.1:8000/api/profile`, formData, headers).then(res => {
console.log(res)
}).catch(e => {
console.log(e)
})
}
Try this way
axios.put(`http://127.0.0.1:8000/api/profile`, {'profile-picture':this.profile.profile_picture}, {
headers: {
Authorization: 'Bearer ' + this.token,
'content-type': 'multipart/form-data'
}
}).then(res => {
console.log(res)
}).catch(e => {
console.log(e)
})
Hope this may solve your problem. For more info read docs

AccessToken from AsyncStorage + request by axios

While writing the application in the react-native I met with a certain obstacle related to promises, so I have a function that is responsible for the authorized request
export const authorizeRequest = async () => {
const token = await deviceStorage.getItem('accessToken');
return axios.create({
timeout: 2000,
headers: {
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/json'
}
});
};
in order to get data from it I write code in the style
authorizeRequest().then(a => a.get('http://192.168.0.60:8080/users/echo2/asd')
.then(response => ToastAndroid.show('Response ' + response.data, ToastAndroid.SHORT))
.catch(error => ToastAndroid.show('error ' + JSON.stringify(error), ToastAndroid.LONG)))
Is it possible to avoid the first use of .then when calling authorizeRequest().then(....) so that the query looks like authorizeRequest().get('xxx').then(xxx).catch(xxx)
Thanks!
Why use promise syntax when you are already using async/await syntax to get your value out of the device storage?
You can rewrite your code using async/await which makes it much easier to see what is going on in your code.
export const authorizeRequest = async (url) => {
try {
const token = await deviceStorage.getItem('accessToken');
const a = await axios.create({
timeout: 2000,
headers: {
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/json'
}
});
const response = a.get(url);
ToastAndroid.show('Response ' + response.data, ToastAndroid.SHORT);
// return response.data // <- you could return something here
} catch (error) {
ToastAndroid.show('error ' + JSON.stringify(error), ToastAndroid.LONG);
}
};
Writing your code in the above way means that you can avoid promise chaining.
You can then use it in the following way:
await authorizeRequest('http://192.168.0.60:8080/users/echo2/asd')
If you want to get a value from the authorizeRequest function you could just return the response.data and you would access it like this:
const data = authorizeRequest('http://192.168.0.60:8080/users/echo2/asd')
Here are some great articles on promises and async/await.
https://medium.com/#bluepnume/learn-about-promises-before-you-start-using-async-await-eb148164a9c8
https://hackernoon.com/6-reasons-why-javascripts-async-await-blows-promises-away-tutorial-c7ec10518dd9

Using Axios GET with Authorization Header in vue App

I'm trying to use axios for a GET request with an API which requires an Authorization header.
here is my current code
My current code:
data () {
return {
listings: [],
AuthStr : 'Bearer ' + JSON.parse(localStorage.getItem('token')),
}
},
created () {
axios.get(`url`, { 'headers': { 'Authorization': AuthStr } })
.then((response => {
this.listings = response.data;
})
.catch((error) => {
console.log(error)
})
}
it shows me 403 error I don't know why.
There are several ways to to add header to request.
For a single request:
let config = {
headers: {
Authorization: value,
}
}
axios.get(URL, config).then(...)
you need to call data().AuthStr to get your token there is a typo.
Your created function will be
created () {
axios.get(`url`, { 'headers': { 'Authorization': data().AuthStr } })
.then((response) => {
this.listings = response.data;
})
.catch((error) => {
console.log(error)
})
}
It should be:
axios.get(`url`, { 'headers': { 'Authorization': this.AuthStr } })
You are using JSON.parse when getting the value for AuthStr. JSON.parse returns an object. Try removing it and if you are using the correct Auth token, it should work.

React Native - Axios POST with urlencoded params

I successfully triggered POST request via Postman to retrieve mobileSession key. But when I tried the same from React Native app (via Axios), I get error that some params are missing. Can someone tell me what is wrong in Axios according to Postman request which is working?
Postman:
And Axios code:
export function getMobileSession() {
let requestOptions = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
let body = {
username: 'myusername',
password: 'mypw',
api_key: 'apikey',
api_sig: 'signature',
method: 'auth.getMobileSession',
format: 'json'
};
return axios.post('Lastfm_API_URL', JSON.stringify(body), requestOptions)
.then(response => {
return response;
})
.catch(err => {
throw err;
});
}
Try this,
return axios.post(`https://ws/audioscrobbler.com/2.0/`, JSON.stringify(body), requestOptions)
.then(response => {
return response;
})
.catch(err => {
throw err;
});
For more refer here to know about back tick.

AXIOS : Send Authorization header returns Error 401, Authorization Header missing

I came around this solution but this is not working for me.
Following is my code:
axios.post('http://myurl/api/login', {
email: 'john#doe.com',
password: '123456'
}, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).then(response => {
if (response.data) {
this.AuthToken = response.data.token
console.log(this.AuthToken)
axios.get('http://myurl/userdetails/:uid', {
uid: 'D123'
}, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': this.AuthToken
}
}).then(response => {
if (response.data) {
// this.AuthToken = response.data
console.log(response.data)
}
}).catch(error => {
console.log('User Data response Error: ' + error)
})
}
}).catch(error => {
console.log('Login Error: ' + error)
})
I'm getting token from the first POST Login API call. I used that toke to pass into another API call as Authentication token. But I get error: Missing Authorization Headers
Found the solution:
axios.defaults.headers.common['Authorization'] = this.AuthToken;
Try to add another header. "Access-Control-Allow-Headers" : "*".