I am attempting to send data along with a file to the server
Currently, I have implemented the following 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]);
Here is the code for sending the 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);
}
};
The response from the server indicates a 422 error with the following 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."]}}
Below are the headers used for the request: https://i.sstatic.net/H3wegSaO.png
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 have tried using XHR and various other methods, but I continue to encounter this issue. Interestingly, when testing with Postman, everything works fine, whereas utilizing JavaScript presents these problems.