How to use axios instead of fetch in react-native? - react-native

I use fetch to send data to webservice. How can I do this with axios ?
fetch('url', {
method: 'POST',
headers: new Headers({
'Accept': 'application/json',
'Content-Type': 'application/json', // <-- Specifying the Content-Type
}),
body: JSON.stringify(object)
})

Here is some code that is close to what you want.
axios({
method: 'post',
url: 'myurl',
data: bodyFormData,
config: { headers: {'Content-Type': 'application/json' }}
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});
Alternately, you can set you configuration then use axois.post(). This axios cheatsheat may help you as well.

Related

Problem with API of Twitch with Axios GET POST

i got problem with codes.
axios({
method: 'post',
url: 'https://id.twitch.tv/oauth2/token',
body: {
client_id: 'a',
client_secret: 'Bearer b',
grant_type: 'client_credentials',}
}).then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
})
and result is :
data: { status: 400, message: 'missing client id' }
but this way works fine if i put them in url :
url: 'https://id.twitch.tv/oauth2/token?client_id=a&client_secret=b&grant_type=client_credentials',
what is my problem?
also can u give me an example for axios.get ? with :
url: 'https://api.twitch.tv/helix/games/top'
headers: {
client_id: 'a',
Authorization: 'Bearer b',
}
For axios you need to be sending as data not body
And then construct/send a FormData
So for example
axios({
method: "post",
url: "myurl",
data: bodyFormData,
headers: { "Content-Type": "multipart/form-data" },
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});
See also: axios post request to send form data
and: https://github.com/axios/axios/issues/318
Using body will get mixed results as the library (axios) won't know how to encode the data being sent
Personally myself I'm using got over axios so I send
got({
url: "https://id.twitch.tv/oauth2/token",
method: "POST",
headers: {
"Accept": "application/json"
},
form: {
client_id: config.client_id,
client_secret: config.client_secret,
grant_type: "client_credentials"
},
responseType: "json"
})
.then(resp => {
//SNIP
apparently the API receives the parameters via URL so it's interesting to pass them as url too.
Ex: axios({
method: 'post',
url: 'https://id.twitch.tv/oauth2/token?client_id=${variable.a}&client_secret=${variable.b}...

using data returned from promise in another fetch not working

I have a handleSubmit function that I have added two post requests to.
However, one of the post requests relies on the data returned from the first post request. I've attempted to access this data by setting it to a var but it doesn't seem accessible within the second fetch. Not sure if my syntax is wrong.. any ideas?
I believe this should be working but I'm not sure where I'm going wrong. Thanks!
handleSubmit = () => {
fetch('http://localhost:3000/resources', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
body: JSON.stringify({
name: this.state.name,
description: this.state.description,
link: this.state.link,
topic_id: this.state.topic_id
})
})
.then(res => res.json())
.then(data => {
this.props.addResource(data)
var dataId = data.id;
})
return fetch('http://localhost:3000/user_resources', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
body: JSON.stringify({
resource_id: dataId,
user_id: this.props.users.id
})
})
.then(res => res.json())
.then(data => {
this.props.addUserResource(data)
})
this.props.navigation.goBack()
}
There's 2 problems:
You return some code and then try to run something else. Your this.props.navigation.goBack() statement will never be reached because the function ends when it reaches the return. That is not your main problem though.
fetch is asynchronous. It means that the function handleSubmit will read the two first statements ("fetch resources" and "return fetch user_resources") and then when each fetch is finished they will run their .then() functions.
This means your dataId will be undefined and you need to wait for the first fetch to complete and to execute the 2nd fetch.
handleSubmit = () => {
fetch('http://localhost:3000/resources', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
body: JSON.stringify({
name: this.state.name,
description: this.state.description,
link: this.state.link,
topic_id: this.state.topic_id
})
})
.then(res => res.json())
.then(data => {
this.props.addResource(data)
return fetch('http://localhost:3000/user_resources', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
body: JSON.stringify({
resource_id: data.id,
user_id: this.props.users.id
})
})
})
.then(res => res.json())
.then(data => {
this.props.addUserResource(data)
})
this.props.navigation.goBack()
}

React Native: Not able to make post request for formData using axios or fetch

I have been trying to make a post request to send formData using axios / fetch, but every time i make a request it throws "Network Error". I have been trying this for couple of days but couldn't do it.
var file = new File([this.state.selectedFileObj], "ISDD_" + this.state.fileName, { lastModified: new Date().getMilliseconds() })
formdata.append("file", file, this.state.fileName);
formdata.append("folderName", this.state.folderName);
formdata.append("userName", "user#domain.com");
formdata.append("documents", documents);
// 1st approach
RNFetchBlob.fetch('POST', url, {
"Content-Type": 'multipart/form-data',
"enctype": 'multipart/form-data',
"Cache-Control": 'sno-cache',
"Pragma": 'no-cache'
}, formdata)
.then((response) => console.log(`1 ${response.text()}`))
.then((RetrivedData) => {
console.log(`2 ${RetrivedData}`);
})
.catch((err) => {
console.log(`err ${err}`);
})
//2nd approach
axios({
url: url, formdata,
method: 'POST',
headers: {
"Content-Type": 'multipart/form-data',
'enctype': 'multipart/form-data',
'Cache-Control': 'sno-cache',
'Pragma': 'no-cache'
},
data: formdata
})
.then((response) => {
console.log(`1 ${response}`)
})
.catch((error) => {
console.log(error)
})
Need a solution for it,
Thanks,

Can't get a .post with 'Content-Type': 'multipart/form-data' to work Axios React Native

i'm trying to upload FormData which include text ,image,pdf etc
I am using axios.
Axios Call
const sellerRegister = params => {
console.log(params);
return dispatch => {
dispatch(servicePending());
return axios
.post(`${BaseUrl}/seller/register`, params, {
headers: {
Accept: "application/json",
"Content-type": `multipart/form-data; boundary=${params._boundary}`
}
})
.then(res => {
return dispatch(sellerRegisterSuccess(res));
})
.catch(err => {
return dispatch(serviceError(err.message));
});
};
};
Params in FormData
ServiceError
Provide solutions of this error. and also guide me am i doing this in right way or not ?
Thanks
Using the latest version of Axios, you make an HTTP request with 'Content-Type': 'multipart/form-data' in the header as follows:
const formData = new FormData();
formData.append('action', 'ADD');
formData.append('param', 0);
formData.append('secondParam', 0);
formData.append('file', new Blob(['test payload'], { type: 'text/csv' }));
axios({
url: 'http://your_host/api/auth_user',
method: 'POST',
data: formData,
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data'
}
})
use url instead of uri.
or
You can do simply:
axios.defaults.headers.common['Content-Type'] = 'multipart/form-data;
boundary=someArbitraryUniqueString';

Mapbox navigation api return 422 unprocessable entity

I'm trying to call the mapbox api to get navigation instructions.
Here's the doc: https://docs.mapbox.com/api/navigation/#using-http-post
And here's my api call:
fetch(`https://api.mapbox.com/directions/v5/mapbox/walking?access_token=${Config.MAPBOX_API_KEY}`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
},
body: JSON.stringify({
coordinates: "2.344003,48.85805;2.34675,48.85727;",
}),
}).then(res => {
console.log(res)
}).catch(err => {
console.log(err)
})
Unfortunately I get a 422 unprocessable entity error:
I have tried differente coordinates as well...do you guys know what am I missing?
You're passing your coordinates in as a string, but the API expects a number, which is why you're getting a 422. Try this:
fetch(`https://api.mapbox.com/directions/v5/mapbox/walking?access_token=pk.eyJ1IjoiYmRkYXZpZHNvbiIsImEiOiJjaW41MWU5bTcwY2k1dXdtNG54cnhlczFsIn0._R6SrAak5_qF8l31JvSBIA`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
},
body: 'coordinates=2.344003,48.85805;2.34675,48.85727', // <--- Body changed to pass numbers instead of strings
}).then(res => {
console.log(res)
}).catch(err => {
console.log(err)
})