React Native - Axios POST with urlencoded params - react-native

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.

Related

Fetch Post of formData with images works in iOS but on android returns 400 BAD REQUEST

`I am using fetch on react native to send a post request with a form data object on the body.
This code works on iOS but on android it returns a 400 BAD REQUEST and I get ERROR [SyntaxError: JSON Parse error: Unexpected EOF].
const buildFormData = () => {
const data = new FormData();
for (let i = 0; i < photoForm.photosToUpload.length; i++) {
console.log(photoForm.photosToUpload[i].uri)
data.append('photosToUpload', {
uri: photoForm.photosToUpload[i].uri,
name: photoForm.photosToUpload[i].fileName,
type: 'image/jpeg'
});
data.append("userForm", JSON.stringify(userForm));
console.log(data)
return data;
}
This is how I am building my form data.
export const createUser = (formData) => async (dispatch) => {
try {
const headers = {
'Content-Type': 'multipart/form-data'
};
const response = await fetch('https://c66d-2a02-a03f-a5a1-e400-1573-78c6-e019-e601.eu.ngrok.io' + '/create_user', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
body: formData,
})
.then(response => response.json())
.then(responseJson => {
console.log(responseJson);
})
.catch(error => {
console.error(error);
});
Handle successful response
catch (error) {
Handle error
}
This is how I am sending the form data to my django server. I know the problem is in the form data because if I dont send files the request goes through.
I have read almost every github issue on this matter, switched to axios, tried multiple solutions and no luck. Does anyone know what the problem can be?
I tried to make a post request using fetch and it works on iOS but not on android.
I was expecting to work on both OS.`

axios cancellation caught inside of then() instead of catch()

I making a multi-upload file form.
Upon user cancellation, once the corresponding axios call get cancelled using cancel(), I having a weird behaviour. My axios call get caught inside the then() whereas it should be caught inside of catch(). The response inside of then() returns undefined.
I am having a hard time figuring if I did something wrong on the front-end part, I think my call is may be missing some headers or maybe it's on the backend part ?
const payload = { file, objectId: articleId, contentType: 'article' };
const source = axios.CancelToken.source();
// callback to execute at progression
const onUploadProgress = (event) => {
const percentage = Math.round((100 * event.loaded) / event.total);
this.handleFileUploadProgression(file, {
percentage,
status: 'pending',
cancelSource: source,
});
};
attachmentService
.create(payload, { onUploadProgress, cancelToken: source.token })
.then((response) => {
// cancelation response ends up here with a `undefined` response content
})
.catch((error) => {
console.log(error);
// canceled request do not reads as errors down here
if (axios.isCancel(error)) {
console.log('axios request cancelled', error);
}
});
the service itself is defined below
export const attachmentService = {
create(payload, requestOptions) {
// FormData cannot be decamelized inside an interceptor so it's done before, here.
const formData = new FormData();
Object.entries(payload).forEach(([key, value]) =>
formData.append(decamelize(key), value),
);
return api
.post(resource, formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
...requestOptions,
})
.then((response) => {
console.log(response, 'cancelled request answered here as `undefined`');
return response.data;
})
.catch((error) => {
// not caught here (earlier)
return error.data;
});
},
};
cancellation is called upon a file object doing
file.cancelSource.cancel('Request was cancelled by the user');
As suggested by #estus-flask in a comment, the issue is that I was catching the error inside of the service (too early). Thank you!
export const articleService = {
create(payload, requestOptions) {
// FormData cannot be decamelized inside an interceptor so it's done before, here.
const formData = new FormData();
Object.entries(payload).forEach(([key, value]) =>
formData.append(decamelize(key), value),
);
return api.post(resource, formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
...requestOptions,
});
},
};

How can I console log axios response outside the request

async login(context, payload) {
const response = await axios
.post(
'https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=AIzaSyCQ6w2jvJVNrOwON4-KnEOV1kH-ckEDokg',
{
email: payload.email,
password: payload.password,
returnSecuredToken: true
},
{
Headers: {
'Content-Type': 'application/json'
}
}
)
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
console.log(error.response);
});
console.log(response);
context.commit('setUser', {
token: response.data.idToken,
userId: response.data.userId,
tokenExpiration: response.data.expiresIn
});
Hello, maybe it's a dumb question but how can I console.log my response there ? I tried to stock my response in a const but it's the same issue, the console log and the commit execute before the await async and I can't use any data that return from the axios response, thanks if you take the time to help me.
You don't need then function in this case. With await word is enough
The problem is your intermediate .then returns nothing, so the return value of await axios.post() resolves to undefined.
You could either remove the unnecessary .then:
const response = await axios.post(/*...*/);
console.log(response);
...or return response in .then:
const response = await axios.post(/*...*/)
.then(response => {
console.log(response);
return response;
});

Axios Get Authorization Not Working In Vue But Worked on POSTMAN (Post method on vue worked)

I'm Using vue for the clientside. And somehow the Authorization is not working with Get method in axios. I tried using POSTMAN and it's working like it should be. Is there any chance that I missed something?
getCurrentPeriode() {
return new Promise((resolve, reject) => {
axios.get(TABLE_NAME,{params: {"X-API-KEY": API_KEY, command:"getCurrent"}}, {
headers:{
'Authorization': `Basic ${token}`
}
})
.then((response) => {
resolve(response.data[0])
}) .catch(err => {
reject(err.response.data)
})
})
}
The token:
const token = Buffer.from(`${username}:${password}`, 'utf8').toString('base64')
I get this error: Uncaught (in promise) {status: false, error: "Unauthorized"}
In postman (it's worked):
I've tried with post method in axios and it's working. Yes I've set up CORS. Yes I've allowed Get method in my server side (coz it's working in postman)
Post method is working like normal, here's the code:
postNewPeriode(date) {
return new Promise((resolve, reject) => {
const data = new FormData()
data.append("dateStart", date.dateStart)
data.append("dateEnd", date.dateEnd)
data.append("X-API-KEY",API_KEY)
axios.post(TABLE_NAME,data, {
headers:{
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": `Basic ${token}`
}
})
.then((response) => {
resolve(response)
}) .catch(err => {
reject(err.response.data)
})
})
},
Am I missing something in my axios get or I should use different approach? Thanks for the answer
For Axios GET, the headers should be the second argument, while for PUT and POST the body is the second and the headers the third, as you did.
Try using the headers as the second argument on GET.
This should work:
axios.get( TABLE_NAME,
{
headers:{'Authorization': `Basic ${token}`},
params: {"X-API-KEY": API_KEY, command:"getCurrent"}
}
)

Fetch with devise_token_auth in react-native

I'm new with react-native. I'm trying to satisfy the devise_token_auth requirement of send in every request the authetication headers. To do so, I'm trying something like this:
export const scheduleFetch = (auth) => {
return (dispatch) => {
fetch(URL, {
method: 'GET',
headers: {
'Content-Type': 'application/json; charset=utf-8',
'access-token': auth['acessToken'],
'token-type': auth['tokenType'],
'client': auth['client'],
'uid': auth['uid']
}
})
.then((response) => {
console.log(response)
response.json()
})
.catch((error) => console.log(error))
}
}
My back-end is receiving the request, all headers are fill. However, I still receiving the message "_bodyText":"{\"errors\":[\"You need to sign in or sign up before continuing.\"]}".
How can I make that work? Am I jumping any step?