0

I created REST API using Express JS to send Excel file:


app.get('/download/', async (req, res) => {
    try {
       await res.download('./ExcelCopy.xlsx');
    } catch (e) {
        res.status(400).send(e);
    }
});

But in Reactjs when I connect to API nothing happens, but redux tells everything went well:

export const getExcel = () => async (dispatch) => {
  await dispatch(getExcelRequest());
  try {
    await axios.get('http://127.0.0.1:8888/download/');
    dispatch(getExcelSuccess());
  } catch (error) {
    console.log(error);
    dispatch(getExcelFailed());
  }
};

What should I do in order to download a file from back-end using react js

2 Answers2

3

You need to add response type and use npm package file-saver to download the file.

Modified Code:

export const getExcel = () => async (dispatch) => {
  await dispatch(getExcelRequest());
  try {
    axios.get('http://127.0.0.1:8888/download/', { responseType: 'arraybuffer' })
      .then((response) => {
         var blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
              fileSaver.saveAs(blob, 'data.xlsx');
              dispatch(getExcelSuccess());

       });        
   } catch (error) {
      console.log(error);
      dispatch(getExcelFailed());
   }
};
Surjeet Bhadauriya
  • 6,755
  • 3
  • 34
  • 52
0

As far as I know, you can not just send a get request to download the file. Instead I would suggest you to use this module named js-file-download.

Example usage:

const FileDownload = require('js-file-download');

const response = await axios.get('http://127.0.0.1:8888/download/')
FileDownload(response.data, 'ExcelCopy.xlsx');

Hope it helps.

Shihab
  • 2,641
  • 3
  • 21
  • 29