Home > database >  Convert fetch to axios
Convert fetch to axios

Time:07-20

I did a 'get' with fetch but I want to do it with axios, could someone help me convert this code to axios?

detail: detail: I made the request to get an image, and I use the blob to be able to show this image to the user, and I would like to do that with axios as well.

Code:

 const image = (url) =>
    fetch(url)
      .then((response) => {
          return response.blob();
      })
      .then(
        (blob) =>
          new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onloadend = () => resolve(reader.result);
            reader.onerror = reject;
            reader.readAsDataURL(blob);
          })
      );

CodePudding user response:

const image = async (url) =>
    await axios.get(url)
    .then(response => {
      // can access blog directly from response... 
    }
    

Read more about axios here

CodePudding user response:

You can do something like this if its a GET request

const image = async (url) => {
   return await axios({
   url: url
   method: 'GET',
   headers: {
     //add headers if any
   }
})
.then((response) => {
  // do whatever you want with your response
}

CodePudding user response:

Here: I am assuming this is a get request?

    const image = async (url) => {
    
   return await axios.get(url)
      .then((response) => {
          return response.blob();
      })
      .then(
        (blob) =>
          new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onloadend = () => resolve(reader.result);
            reader.onerror = reject;
            reader.readAsDataURL(blob);
          })
      );
    }
  • Related