I am trying to send data with file to server
I have code on vue 3
const formData = new FormData();
formData.append('responsible_name', groupForm.value.responsibleName);
formData.append('responsible_phone', groupForm.value.responsiblePhone);
formData.append('responsible_email', groupForm.value.responsibleEmail);
formData.append('appeal_type_id', groupForm.value.appealTypeId);
formData.append('municipality_id', groupForm.value.municipalityId);
formData.append('educational_institution_id', groupForm.value.educationalInstitutionId);
formData.append('users', groupForm.value.users);
formData.append('flows', groupForm.value.flows.filter((flow: EventFlow) => flow.select).map((flow: EventFlow) => flow.id));
formData.append('appeal_doc', fileInput.value.files[0]);
I have next code for sending data
const headers = {
'Content-Type': 'multipart/form-data',
Accept: 'application/json',
'Access-Control-Allow-Origin': '*',
'Cache-Control': 'no-cache',
};
const makeAppeal = async <T>(body: BodyFetchData): Promise<T> => {
try {
const data = await fetchData('/appeal/create', 'POST', body, headers);
return data as T;
} catch (e) {
return Promise.reject(e);
}
};
Basically, fetchData is $fetch from vue3.
Then I have next response from server. 422 error and next messages
{"message":"The flows field is required. (and 4 more errors)","errors":{"flows":["The flows field is required."],"responsible_name":["The responsible name field is required."],"responsible_phone":["The responsible phone field is required."],"responsible_email":["The responsible email field is required."],"users":["The users field is required."]}}
I have next headers for request
const fetchData = async <T>(url:string, method: MethodFetchData = 'GET', body: BodyFetchData = '', headers: Record<string, string> = {}): Promise<T> => {
const apiUrl = `${useRuntimeConfig().public.domainApi}${url}`;
const headersDefault = {
'Content-Type': 'application/json',
Accept: 'application/json',
'Access-Control-Allow-Origin': '*',
...headers,
};
try {
if (method === 'GET') {
const data = await $fetch(apiUrl, { headers: headersDefault, method, params: body || {} });
return data as T;
}
if (method === 'POST') {
const data = await $fetch(apiUrl, { headers: headersDefault, method, body });
return data as T;
}
return Promise.reject();
} catch (error) {
return Promise.reject(error);
}
};
I am tried use xhr and many many variants for using this. When I use postman it's ok, but with js I have this problems
I found solution for my problem. I saw that I don't have header with boundary x, that generates dynamically for multipart/formdata.
Solution for problem was here appending array to FormData and send via AJAX
I just remove all my headers except:
Accept: 'application/json',