Home > front end >  How to switch from Fetch to Axios
How to switch from Fetch to Axios

Time:08-25

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

CodePudding user response:

To make the response type of axios with text, you just need to pass responseType: 'text' and transformResponse: undefined to the options object.

const createAttachment = async (formData: FormData): Promise<boolean | string> => {
  try {
    const resultText = await axios(API_URL, { method: 'POST', body: formData, responseType: 'text', transformResponse: undefined });

    return resultText;
  } catch (error) {
    captureMessage(`Kontaktní formulář selhal při nahrávání přílohy: ${error}`);
    return false;
  }
};

CodePudding user response:

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;
  • Related