FormData give axios network error in react native - reactjs

This runs okay and request sent to the server successfully
axios({
method: "post",
url: `http://192.168.1.12:8000/user/image`,
data: {formData}
})
.then((res) => {
console.log(res)
})
.catch((err) => {
console.log(err)
})
But this gives axios network error:
axios({
method: "post",
url: `http://192.168.1.12:8000/user/image`,
data: formData
})
.then((res) => {
console.log(res)
})
.catch((err) => {
console.log(err)
})
I am using it the same way in my other project(react) but that works fine, here in this project(react-native) it gives axios network error if I don't enclosed the formData in {}.
Here is react frontend:
Here is react backend, as you can see I am getting the req.file and req.body does not have the formData:
Here is react-native result, formData is coming in req.body and req.file is undefined:

pass the headers likewise -
axios({
method: "post",
url: `http://192.168.1.12:8000/user/image`,
data: formData,
headers: { "Content-Type": "multipart/form-data" },
})
.then((res) => {
console.log(res)
})
.catch((err) => {
console.log(err)
})

Related

How to send a image jpg/png file from react to express server

I am trying to send an object from react to express server using node.js
this is my object:
const formData = {
location: location,
cost: cost,
email: email,
image: image,
};
This is my fetch post method :
fetch("http://localhost:5000/places", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(formData),
})
.then((res) => res.json())
.then((data) => {
if (data.insertedId) {
alert("Plcae added successfully");
}
})
.catch((error) => {
console.error("Error:", error);
});
I can see the image file object in client site console but I am not getting that in expreess server.
You have to send your input data as FormData to share images/files to the backend.
function uploadImage() {
let formData = new FormData(yourFormData);
fetch("http://localhost:5000/places", {
method: "POST",
body: formData,
}).then((res) => res.json())
.then((data) => {
if (data.insertedId) {
alert("Plcae added successfully");
}
})
.catch((error) => {
console.error("Error:", error);
});
}

Axios response showing status code 200 but no response data

I'm a newbie to axios. I'm trying to send a post request with an authorization header. The response data is returned in Post man. But I couldn't see any response data in my browser. Please help.
axios.post('http://13.127.3.151:8080/v1/dashboard/getuserdetails', {
utype: "staff",
uemail: "abdulwahidnasir#bitsathy.ac.in"
},
{ headers: { 'Authorization': `Bearer ${serviceToken}`,
'Content-Type': 'multipart/form-data' } })
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error.response)
});
I have found the problem, it was with formData. This works fine now.
let formData = new FormData();
formData.append("utype", userType);
formData.append("uemail", email);
axios.post('http://13.127.3.151:8080/v1/dashboard/getuserdetails', formData,
{ headers: { 'Authorization': `Bearer ${serviceToken}`,
'Content-Type': 'multipart/form-data' } })
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error.response)
});

Making Two API calls in react using axios

I am making an app where I send and receive data from one API. Once I get this data I want to make another call to the some other API sending this data to this second API and receiving data from this second API.
export const uploadImage = (data) => (dispatch) => {
dispatch({ type: UPLOAD_IMAGE });
axios({
method: 'post',
url: 'http://3.14.136.182:80/predict',
data: data,
"mimeType": "multipart/form-data",
headers: {
'content-type': 'multipart/form-data'
},
timeout: 20000
})
.then((response) => {
dispatch({ type: UPLOAD_IMAGE_SUCCESS, payload: response.data });
data = response.data;
axios({
method: 'post',
url: '3.14.136.182:8005/finalResult',
data: data,
"mimeType": "multipart/form-data",
headers: {
'content-type': 'multipart/form-data'
},
timeout: 20000
})
.then((response) => {
dispatch({ type: UPLOAD_IMAGE_SUCCESS, payload: response.data});
console.log("Mehmood",response.data);
})
.catch((error) => {
dispatch({ type: UPLOAD_IMAGE_FAILURE });
})
})
.catch((error) => {
dispatch({ type: UPLOAD_IMAGE_FAILURE });
})
}
You are missing at one return statement in you first then block. (before axios). Also you are dispatching success two times.

Api call works on postman but Doenst work on my code

So I have to update some user info ,it works fine on postman but when I try to type it in react-native I must be doing something wrong in the body of the fetch method. In postman I set x-www-form-urlencoded and type the keys like this :
Key ----- Value
moto ----- test
and that seems to work,but when I try to do the same on my code I somehow fail at it,here is my code
updateUser(){
return fetch(url,{
method: "PATCH",
headers: {
"X-Auth-Token": bearerToken,
"Content-Type":"application/x-www-form-urlencoded"
},
body: JSON.stringify({
moto: this.state.moto
}
})
}
)
I get 200 response which means the call works but I must be seting the parameter moto wrong somehow.
Any ideas ?
"Content-Type":"application/x-www-form-urlencoded"
should be
"Content-Type":"application/json"
form-urlencoded is way different from your body: JSON.stringify().
You'll want to use a FormData object instead:
const body = new FormData();
body.append('moto', this.state.moto);
fetch(url, {
method: "PATCH",
headers: {
"X-Auth-Token": bearerToken,
"Content-Type": "application/x-www-form-urlencoded"
},
body,
})
APICall = () => {
fetch(‘Your http URL’, {
method: 'PATCH',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
‘X-Auth-Token’: bearerToken,
},
body: JSON.stringify({
moto: this.state.moto
})
}).then((response) => response.json())
.then((responseJson) => {
if(responseJson.statuscode == 1) {
Alert.alert('Success');
} else {
Alert.alert(responseJson.message);
}
}).catch((error) => {
console.error(error);
});
}
finally fixed it by seting body to
body:
`moto=${this.state.moto}`
it appears that urlencoded headers require parameters in the form of
parameter1=value1&parameter2=value2
componentDidMount() {
return fetch(“Your URL”, {
method: 'post',
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8",
"Authorization": “token”
},
body: "firstName=Nikhil&favColor=blue&password=easytoguess"
})
.then((response) => response.json())
.then(function (data) {
alert(“Success”)
console.log('Request succeeded with JSON response', data);
})
.catch(function (error) {
alert("error occur")
console.log('Request failed', error);
});
}
const formData = new FormData();
formData.append('email', 'test#gmail.com');
formData.append('password', '123456');
fetch("https://test.com/api/login", {
method: 'post',
body: formData
})
.then(res => res.json())
.then(
(result) => {
console.log(result);
}).catch(err => {
console.log(err);
})

Fetch request always returns network error

I almost finished creating React Native application, few days ago register action has stopped working.. I'm sending fetch request and it always returns network error altough there is 400 response and message that user exists, it stops there..
I'm destructuring the response and displays api response message instead of fetch network error but now it doesn't work. I'm doing the same for the login action and it works.
Could it be something with multipart/form-data ?
export const register = data => dispatch => {
dispatch(createUser());
const d = new FormData();
d.append("name", data.name);
d.append("email", data.email);
d.append("password", data.password);
d.append("avatar", data.avatar);
fetch(API_URL + "/register", {
method: "POST",
headers: {
"content-type": "multipart/form-data"
},
body:d
})
.then(response => response.json().then(user => ({ user, response })))
.then(({ user, response }) => {
if (!response.ok) {
console.log(response, user)
} else {
console.log(response, user)
}
})
.catch(err => {
throw err;
});
};
The api route works in Postman..
In this case, your using fetch which is Promise based incorrectly,
Try,
fetch(API_URL + "/register", {
method: "POST",
headers: { "content-type": "multipart/form-data" },
body:d
})
.then(response => {
console.log(response, response.json().user)
})
.catch(err => {
console.log(err)
});
Check the logs and see if it shows proper network response and debug from there.

Resources