how make put axios request with formData? - vue.js

i tried to send data with text and file. i created formData to send it:
updateProduct(item){
let product = new FormData();
product.append('thumb', item.thumb)
product.append('weight', item.weight)
this.$store.dispatch('UPDATE_PRODUCT', product)
},
action in store:
UPDATE_PRODUCT({commit}, item){
const token = localStorage.getItem('token');
const config = {
headers: { Authorization: `Bearer ${token}`}
};
// console.log(token)
return axios.post(`${url}`, item, config)
.then((resp) => {
commit('UPDATE_PRODUCT_IN_STATE', resp)
return resp;
})
.catch((error) => {
console.log(error);
});
},
So i have 422 error. Why?

Related

Upload Image With Expo & Fetch

I am trying to upload an image from my react native app.
If I use my local node server and run this code:
var fs = require("fs");
var options = {
method: "POST",
url: "my_URL",
headers: {},
formData: {
file: {
value: fs.createReadStream("../../assets/image.png"),
options: {
filename: "image.jpg",
contentType: null
}
}
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
});
I have a succesful upload.
However, with the URI from that we get through the the app, it does not work:
Here is my code on React Native Expo:
const body = new FormData();
body.append("file", 'file:///path/to/file/image123.jpg');
fetch(url, {
method: "POST",
body,
headers: {
"content-type": "multipart/form-data"
}
})
.then(response => {
console.log(response, "RESPONSE");
})
.then(result => {
console.log(result, "RESULT");
})
.catch(error => {
console.log(error, "ERROR");
});
I am unable to get it to work. I think it has something to do with the file path from the device.
Any help will be appreciated.
try to create FormData using this function
const createFormData = (uri) => {
const fileName = uri.split('/').pop();
const fileType = fileName.split('.').pop();
const formData = new FormData();
formData.append('file', {
uri,
name: fileName,
type: `image/${fileType}`
});
return formData;
}
if it doesn't work check permissions

how to make the photo field optional in react native

in React native can anyone tell me how to make the responsePath optional thats how i make it optional using && but it is not working in case of photo field can anyone help me out below are the codes.first is of redux how i send the data using formdata and 2nd is of component where i called this api function of redux.
redux//
export const addMember = (formValues, actions, key, resourcePath) => {
return async dispatch => {
const token = await AsyncStorage.getItem('userToken');
const formdata = new FormData();
formdata.append('name', formValues.name);
formdata.append('age', formValues.age);
formdata.append('relation', formValues.relation);
formdata.append('gender', key);
formValues.mobile && formdata.append('mobile', formValues.mobile);
formValues.blood_group &&
formdata.append('blood_group', formValues.blood_group);
formValues.height && formdata.append('height', formValues.height);
formValues.weight && formdata.append('weight', formValues.weight);
formValues.email && formdata.append('email', formValues.email);
resourcePath && formdata.append('photo', resourcePath);
console.log(formdata, 'for mdata');
let response = await fetch(
'https://theeasylab.com/admin/api/auth/add-family-member',
{
method: 'post',
body: formdata,
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'multipart/form-data',
},
},
)
.then(res => {
return res;
})
.catch(error => {
actions.setErrors(error?.response?.data.error);
return error.response;
});
dispatch({
type: 'ADD_MEMBER',
payload: response,
});
};
};
component //
submitAddMemeber = (values, actions) => {
this.props
.addMember(
values,
actions,
this.state.itemValue.key,
this.state.resourcePath
)
};

React native im trying to upload image everytime localuri.slpit not defined showing and {_parts:[[]]} and why this _parts coming while sending data

can anyone tell me what wrong with this code im trying to upload image using react-native-image-picker in react native.but it says localUri.split is not defined and sending data shows in inspect element as {_parts:[[]]} and why this _parts coming every post method ...please help me to figure out this..
const takeAndUploadPhotoAsync = async () => {
const token = await AsyncStorage.getItem("userToken");
let result = await launchImageLibrary();
if (result.cancelled) {
return;
}
let localUri = result.uri;
let filename = localUri.split('/').pop().split('#')[0].split('?')[0]
let match = /\.(\w+)$/.exec(filename);
let type = match ? `image/${match[1]}` : `image`;
const url = `/auth/upload-prescription`;
let formData = new FormData();
formData.append("file", { uri: localUri, name: filename, type });
setLoading(true);
const response = await api
.post(url, formData, {
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'multipart/form-data',
},
})
.then((res) => {
showMessage({
message: "Your Prescription is Uploaded Successfully",
textStyle: {textAlign:'center'},
type: "success",
backgroundColor: "#202877",
});
})
.catch((error) => {
console.log(error.response);
});
dispatch({
type: "TAKE_AND_UPLOAD_PHOTO_ASYNC",
payload: response,
});
setLoading(false);
};

React native cli formdata is sending data in a object it should not be in any object and array

im trying to post data using formdata but formdata sending data in a object..it should not be in any object or array,,in Reactjs web its working fine it just send like this lab_id : 1 ..how can i solve this issue ..please let me know what can i do,,,
//data is sending like this
{"_parts" : [[
['date', current_date],
['test_ids[]', tests_data],
['lab_partner_id', lab_id],
['booking_for', selectedMember],
['time', time_slot],
['health_package_id', health_packages_details],
['payment_mode', payment_mode],
]]},
// it should be like this only
health_package_id: health_packages_details
//my code
const onPay = async (
current_date,
tests_data,
lab_id,
selectedMember,
time_slot,
health_packages_details,
payment_mode,
) => {
const token = await AsyncStorage.getItem('userToken');
dispatch(startSubmitting());
const url = `/auth/make-booking`;
let formdata = new FormData();
formdata.append('lab_partner_id', lab_id);
formdata.append('booking_for', selectedMember);
formdata.append('date', current_date);
formdata.append('time', time_slot);
health_packages_details &&
formdata.append('health_package_id', health_packages_details);
tests_data && formdata.append('test_ids[]', tests_data);
formdata.append("payment_mode", payment_mode);
const response = await api
.post(
url, formdata ,
{
headers: {
Authorization: `Bearer ${token}`,
},
},
)
.then(res => {
console.log("res hhh", res);
if (res.data.payment_mode == "ONLINE") {
initiatePaymentInterface(res.data);
}
dispatch({
type: 'BOOKING',
payload: response,
});
setLoading(false);
initiatePaymentInterface(res.data);
return res;
})
.catch(error => {
actions.setErrors(error.response.data.error);
failedPaymentInitiate(error.response);
setLoading(false);
});
dispatch(stopSubmitting());
};

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