PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, October 13, 2022

[FIXED] How to switch from Fetch to Axios

 October 13, 2022     axios, fetch-api, javascript, reactjs, typescript     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing