Home > other >  I am trying to implement a file downloading app in react but its not downloading
I am trying to implement a file downloading app in react but its not downloading

Time:04-23

This is the frontend code the error is showing there is no promise returned by the Axios.

import Axios from "axios"
import FileDownload from "js-file-download";
import './App.css';
const download=(e)=>
{console.log(e);
  e.preventDefault()
  Axios({url:"https://localhost:3001",
    method:"GET",
    responseType:"blob"
  }).then((res)=>{
    console.log(res);
    console.log(res);
    FileDownload(res.data,"download.png")
  })

}
function App() {
  return (
    <div className="App">
      <button onClick={(e)=>download(e)}>download</button>
    </div>
  );
}

export default App;

This is the server-side code (backend)


    const express= require("express")
    const cors= require("cors")
    const app =express()
    app.use(cors())
    app.get('/',(req,res)=>{
        console.log('caled');
        res.download("xx.png",(err)=>{
            if(err)
            console.log(err);
        })
    })
    app.listen(3001,(res)=>
    {
        console.log("working on port 3001");
    });

Code in editor

Screenshot of error on console

CodePudding user response:

You need to do the next steps:

  1. Remove 'https://' from axios call:

Axios({url:"https://localhost:3001"}) -> Axios({url:"localhost:3001"})

  1. To fix cors Issue you need to update Axios option with parameter 'withCredentials: false':

Axios({ url: "localhost:3001/", method: "GET", responseType: "blob", withCredentials: false, })

  1. If it didn't help you can use fetch instead of Axios:
fetch('http://localhost:3001', {})
.then( res => res.blob() )
.then( blob => {
    console.log(blob);
});

CodePudding user response:

Maybe it's because you didn't use async / await or lifecycle

  • Related