0

I am trying to download a file in user's machine on clicking a button(ReactJs), which is hitting a post API (express, nodeJs)

here's my code in frontend.


import React from "react";
import download from 'downloadjs';

const downloadFileButton = () => {
  const downloadFile = async (e, item) => {
    e.preventDefault()
    try {
      const responseData = await fetch({
        url: `apiUrl`,
        method: 'POST',
        body: JSON.stringify({
          fileName: item.file_name,
        }),
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${authToken}`
        }
      })
      if (responseData) {
        const file = await responseData.blob()
        download(file, "test.txt");
      }
    } catch (err) {
      return alert(err.message)
    }
  }
  return (
    <button to='vehicleStatus' onClick={e=>downloadHandler(e,item)}>
      <span class="material-icons-outlined green">file_download</span>
    </button>
  )
}

export default downloadFileButton;

here's my code in backend

const downloadSoftware = async(req, res, next) => {
  await sequelize.sync();
  let downloadfile;
  console.log(req.body)
  try{
    downloadfile = await downloadFromFtpServer(req.body.fileName)
    // above line is able to download file from ftp server successfully and store it in downloads folder
    if (downloadfile.code >= 400 || downloadfile.error) {
      console.log('err',downloadfile)
    }
    res.status(200).sendFile(path.resolve(__dirname, '../../downloads/', req.body.fileName));
  } catch(err){
    console.log(err)
    return next(err);
  }
}

This is the error I am getting in frontend "Unexpected token 'h', "hello2" is not valid JSON" Here you can see "hello2" is the content of the file that I am sending from backend.

0 Answers0