Home > front end >  How to add authorization header to a react download button?
How to add authorization header to a react download button?

Time:07-12

I have a button where the logged user can download a file which is stored in the database and is fetched by react from node js/express js. Without authentication I can easily do that by just an tag. But with authentication I am struggling a lot.

React:

const handleDownload = async () => {
    const result = await fetch (process.env.REACT_APP_BACKEND_URL   `/files/download/${props.id}`, {
      headers: {'Authorization': auth.token}
    });

    const responseData = await result.json();
    return responseData;
  }

return (
  <button onClick={handleDownload}>Download File</button>
)

Express js:

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));
  }
  console.log(filePost.file);
  res.download(filePost.file);
};

CodePudding user response:

possible solutions:

  • verify that your auth.token really contains the token (try a console.log for example)
  • if you're using a bearer token do this: {'Authorization': "Bearer " auth.token}

CodePudding user response:

from backend side you will need to do some changes learn jwt authentication or anyother authentication technique for backend and make sure that it works with frontend

how this app will work is when user is not logged in and he clicks on download backend verifies the token and if token is invalid or doesnt exist it send the error through resopnse and frontend shows it on ui

  • Related