How to download files in React from Node server?

My backend:

router.get('/download/:fid', filesControllers.downloadFile);


const downloadFile = async (req, res, next) => {
  const fileId = req.params.fid;
  let filePost;
  try {
    filePost = await File.findById(fileId);
  } catch (err) {
    return next(new HttpError("Error", 500));

If I paste in the browser: ‘http://localhost:5000/api/files/download/fileId’, the file can be downloaded.

My frontend:

<Link to={`http://localhost:5000/api/files/download/${}`} target="_blank" download>
  Download File

When I click on the link, the file fails to download. Is there anything I should do? I have tried with fetch api try/catch block but still couldn’t get it to work.

>Solution :

Go for simple anchor tags.

React-router’s Link tags are good if that page lies on one of your routes. Otherwise, just use a simple anchor tags

<a href={article.url} target="_blank">
  <img src={article.urlToImage} alt="thumb"/>

Leave a Reply