Messed data object in response with Axios - 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);
}
})();

Related

How to send JWT with axios get request?

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

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 to code Multipart-form POST REQUEST using apollo-datasource-rest

I want to code the multipart-form POST REQUEST below using apollo-datasource-rest
My attempt to code this leads to a BAD REQUEST error
const { RESTDataSource } = require('apollo-datasource-rest');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
class SalesforceApi extends RESTDataSource {
constructor() {
super();
this.initialize({});
this.getAccessToken()
.then((accessToken) => {
this.headers = {
Authorization: `Bearer ${accessToken}`,
};
});
}
async getAccessToken() {
console.log('Getting Salesforce access token');
try {
const response = await this.post(
'https://test.salesforce.com/services/oauth2/token',
{
username: 'FILTERED#FILTERED',
password: `${'FILTERED'}`,
grant_type: 'password',
client_id: 'FILTERED',
client_secret: 'FILTERED',
},
{
headers: {
'Content-Type': 'multipart/form-data',
},
},
);
const { accessToken } = response;
console.log(`ChangeGear sessionId: ${accessToken}`);
return accessToken;
} catch (error) {
console.log(`${error}`);
}
return 'No access token!!!';
}
module.exports = SalesforceApi;
[server:salesforce:local] POST https://test.salesforce.com/services/oauth2/token (343ms)
[server:salesforce:local] Error: 400: Bad Request
If memory serves correctly, form data is serialized slightly differently hence why the FormData interface exists. And the apollo-datasource-rest's this.post method is just a wrapper around fetch, so something like the below should work.
Instead of passing the body as a JSON object, try something like this
const formData = new FormData();
formData.append('username', 'FILTERED#FILTERED');
// ... more append lines for your data
const response = await this.post(
'https://test.salesforce.com/services/oauth2/token',
formData
{
headers: {
'Content-Type': 'multipart/form-data',
},
},
);

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