Issue
i am refactoring a code and need to switch from fetch to axios. i got following code:
const createAttachment = async (formData: FormData): Promise<boolean | string> => {
try {
const response = await fetch(API_URL, { method: 'POST', body: formData });
const resultText = await response.text();
if (response?.ok) {
return resultText;
}
// sending fails
captureMessage(
`Kontaktní formulář selhal při nahrávání přílohy: ${JSON.stringify(resultText)}`,
);
return false;
} catch (error) {
captureMessage(`Kontaktní formulář selhal při nahrávání přílohy: ${error}`);
return false;
}
};
i just cant resolve how to get response.text() in axios ?
This is how i am using axios:
const api = axios.create({baseURL: env.STRAPI_URL})
const createAttachment = async (formData: FormData): Promise<boolean | string> => {
try {
const response = await api.post(DAKTELA_FILE_API, formData);
const resultText = await response.data
if (response.statusText === "OK" && response.status === 200) {
return resultText;
}
// fail to send
captureMessage(
`Kontaktní formulář selhal při nahrávání přílohy: ${JSON.stringify(resultText)}`,
);
return false;
} catch (error) {
captureMessage(`Kontaktní formulář selhal při nahrávání přílohy: ${error}`);
return false;
}
};
Solution
The response data will be in the 'data' field of resolved response https://github.com/axios/axios#response-schema
You can post the formData using Axios in this way, without the extra await for extracting the text.
const response = await axios.post(API_URL, formData);
const resultText = response.data;
Answered By - Denis Answer Checked By - Candace Johnson (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.