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);
};
possible solutions:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.