How to send JWT with axios get request? - axios

I tested with postman all works good but when I use axios nothing works
I did like this
const config = {
headers: {
'Authorization': `Bearer ${token}`
}
}
const data = await axios.get(endpoint, config)
And like this
let reqInstance = axios.create({
headers: {
Authorization : `Bearer ${token}`
}
})
const data = await reqInstance.get(endpoint);
Nothing works

Related

Messed data object in response with Axios

I'm making a request for getting an access_token to an auth0 API.
The request is success, but the data object containing the access token contains weird characters. The thing is that I had that object for 3-4 hours, after that it wasn't retrieved anymore. Any clues on this?
And this is the code:
(async () => {
const client = axios.create({
baseURL: 'https://my_url_to.auth0.com/oauth/token',
headers: {
'Content-Type': 'application/json'
}
});
Log.debug(body);
try {
const resp = await client.post('/', body);
console.log(JSON.stringify(resp.data));
} catch (e) {
Log.error(e);
}
})();
In v1.2.1 fixed this error.
You need to add Accept-Encoding with 'application/json' in axios header.
The default of axios is gzip.
This code will be works
(async () => {
const client = axios.create({
baseURL: 'https://my_url_to.auth0.com/oauth/token',
headers: {
'Content-Type': 'application/json',
'Accept-Encoding': 'application/json'
}
});
Log.debug(body);
try {
const resp = await client.post('/', body);
console.log(JSON.stringify(resp.data));
} catch (e) {
Log.error(e);
}
})();

How to authorize to GitHub API using axios

How can I authorize to https://api.github.com using GitHub auth token and axios?
const axiosInstance = axios.create({
baseURL: 'https://api.github.com',
headers: {
Authorization: 'Bearer AUTH_TOKEN_HERE'
}
});
let response = await axiosInstance.get('/');
const fetchRepo = async () => {
const response = await axios.get(URL, {
method: "GET",
headers: {
'Authorization': 'token AUTH_TOKEN_HERE',
}
});
console.log(await response);
return response.data;
}

How do I add body for PayPal partial refund to Axios?

I'm trying to post a partial refund to PayPal using Axios. If I use an empty object as the body I can complete a full refund. But I don't know how to add a body that will complete a partial refund. Here is my current code:
const axios = require('axios');
const qs = require('qs');
const refund = await axios.post("https://api-m.sandbox.paypal.com/v1/payments/capture/"
+ "myTransactionID" + "/refund",
qs.stringify({data:{amount:{currency_code:'USD',value:'20.00'}}}), //this works if I just use {};
{
headers: {
"Content-Type": `application/json`,
"Authorization": `Bearer ${ "myPayPalAccessToken" }`
},
});
console.log("refund: " + JSON.stringify(refund));
I get a "Request failed with status code 400" when I do this. I'm not sure if using a data object is necessary. Please help me figure out the syntax.
I figured it out. I should have been using application/json for the Content-Type. There was no need to stringify the body:
const axios = require('axios');
const qs = require('qs');
const PAYPAL_OAUTH_API = 'https://api.sandbox.paypal.com/v1/oauth2/token/';
const PAYPAL_PAYMENTS_API = 'https://api.sandbox.paypal.com/v2/payments/captures/';
const PayPalAuthorization = await axios({
method: 'POST',
url: PAYPAL_OAUTH_API,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Access-Control-Allow-Credentials': true
},
data: qs.stringify({
grant_type: 'client_credentials'
}),
auth: {
username: PAYPAL_CLIENT,
password: PAYPAL_SECRET
}
});
const PayPalToken = PayPalAuthorization.data.access_token;
const refund = await axios({
url: PAYPAL_PAYMENTS_API + "myTransactionID" + '/refund',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${ PayPalToken }`
},
data: {
amount: {
value: "10.99",
currency_code: "USD"
},
invoice_id: "INVOICE-123",
note_to_payer: "Defective product"
}
});
If you are posting an invoice_id don't forget to change the number for subsequent refunds.
Also check out these links:
https://developer.paypal.com/docs/checkout/integration-features/refunds/
https://developer.paypal.com/docs/api/payments/v2#captures_refund

axios post request fails with bad request

I try to do a simple post request with axios.
My code snippet:
const getOauthToken = async () => {
try {
const headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'X-ProxyPass' : '...',
}
const data = {
...
}
return await axios.post('/oauth2/token', data, {headers: headers});
} catch (error) {
throw new Error(`Unable to get an authentication token. Reason ${error}`);
}
};
This call fails with http 400. When I set the headers as default with
axios.defaults.headers.post['X-ProxyPass'] = '...';
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
then it works.
Found the solution in the documentation of axios.
If I use "application/x-www-form-urlencoded", I have to use querystring to serialize in the needed format.
return await axios.post('/oauth2/token', querystring.stringify(data), {headers: headers});
But why it works, when I set the headers as default headers i still mysterious.

Posting Images using formData to a Django Rest API

I have a Django Rest API backend and am using a React Native Front End. I wanted to save an image to the rest API.
The POST method used is as follows:
async saveUserData() {
let accessToken = await AsyncStorage.getItem(ACCESS_TOKEN);
var formData = new FormData();
formData.append("bio",this.state.bio);
formData.append("website",this.state.website);
formData.append("phoneno",this.state.phoneno);
formData.append("gender",this.state.gender);
formData.append("avatar",this.state.avatar.uri);
try {
let response = await fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
'Authorization': ' Token '+accessToken,
},
body: formData
});
let responseJson = await response.text();
if(response.status>=200&&response.status<300){
console.log("POST Completed");
}else{
let error=responseJson;
console.log(error);
throw error;
}
return responseJson;
} catch(error) {
return error;
console.error(error);
}
}
I get the following error
{"avatar":["The submitted data was not a file. Check the encoding type on the form."]}
I have also tried this.state.avatar.data and tried to post it but I end up getting the same error. I know that the file upload works fine as I can do it properly from the REST Autogenerated form. What seems to be the problem in the image I am posting?
Here is how you can do it:
var formData = new FormData();
formData.append('avatar', {uri: this.state.avatar.uri, name: 'yourname.jpg', type: 'image/jpg'});
let response = await fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
'Authorization': ' Token '+accessToken,
},
body: formData
});