I currently have a front end React app on my localhost at port 8080 and a backend Express server on port 9000 (I think these have to be different ports but I may be wrong). My goal is to have links on my webpage that will download PDFs (or other files like Excel sheets) to a user's local machine but I am unsure how to go about this.
If I have the PDFs on the Express server side I thought of 2 options
- Create a static folder in Express which holds all the file
const app = express();
app.use('/static', express.static(path.join(__dirname, 'MyPDFs')));
and then user anchor tags in my React app to point to the files I need
<a href="http://localhost:9000/static/myFile.pdf">Link to PDF </a>
- Setup routes in Express and send response downloads
var express = require("express");
var router = express.Router();
/* GET home page. */
router.get("/static", function (req, res, next) {
res.download("MyPDFs/myFile.pdf");
});
and then make Http requests from React using fetch or the axios package like I found from this link
axios({
url: 'http://localhost:9000/static',
method: 'GET',
responseType: 'blob',
}).then((response) => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'file.pdf');
document.body.appendChild(link);
link.click();
});
But this solution doesn't seem very clean as I have read that browsers do not natively support downloading files from requests and I need 3rd party packages to do this.
The whole other entire option is to place these files in a directory on the front end React app but I would prefer not to do that. I would prefer to keep these PDFs (or other files like Excel) on the server side and somehow retrieve these files from React. I don't necessarily need these files to be downloaded when a user clicks a link (although thats preferable), but at least to have it display in the browser.
What is the "best practice / standard" approach for this situation? Do PDF files go on the server side or client? Should I simply link to the files on the other port or send Http requests, or something else? Thank you in advance.