Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

131
Visualizações
How to add authorization header to a react download button?

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);
};
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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}
about 4 years ago · Juan Pablo Isaza Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda