-1

This is the error I am getting while download a file from node server. enter image description here

and the file is downloading but the name is not correct what I am providing because the fetch is not accessing it's response section. enter image description here

This is the download file function that fetches the .pdf file from node server.

downloadFileHandler = async (name, path) => {
this.setState({ cvDownloadLoading: true });
try {
  const response = await fetch(
    `${process.env.REACT_APP_SERVER_URL}/${path}`
  );
  if (!response.ok) throw response;
  const buffer = await response.arrayBuffer();
  const url = window.URL.createObjectURL(new Blob([buffer]));
  const element = document.createElement('a');
  element.style.display = 'none';
  element.href = url;
  element.setAttribute('download', name);
  document.body.appendChild(element);
  element.click();
  this.setState({ cvDownloadLoading: false });
  window.URL.revokeObjectURL(element.href);
  document.body.removeChild(element);
} catch (err) {
  this.setState({ cvDownloadLoading: false });
  if (err.name === 'AbortError') {
  } else {
    try {
      // const body = await err.json();
      console.log(err);
    } catch (e) {
      console.log('catch', e);
    }
  }
}

};

The backend node has 'cors' installed and app is using this.

const cors = require('cors');
app.use(cors());

And serving files statically like this.

app.use('/data', express.static(path.join(__dirname, 'data')));

EDITED: Now I tried to download image file and it downloaded without any issue. It is a problem with PDF downloads or any file not image (maybe). Can anyone explain?

talha_ah
  • 314
  • 6
  • 12

1 Answers1

-1

I think you must to config your cors settings and add your client domain in the origin field. Try like this:

const corsOptions = {
   origin: 'http://localhost:8080'
};
// and then
app.use(cors(corsOptions));

You can see this exapmle in Configuring CORS section here https://expressjs.com/en/resources/middleware/cors.html

Oro
  • 2,250
  • 1
  • 6
  • 22