I have an application that renders a file on the server side. I am passing it as "base64" string through json. I need to decode and download a file on the client side. I have presented the code in a simplified form, leaving what is relevant to the question.
Here is the route on the express server:
let xlsx = require('node-xlsx').default;
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
const data = [[1, 2, 3], ['a', 'b', 'c']];
var buffer = xlsx.build([{ name: "mySheetName", data: data }])
.toString('base64');
res.json(buffer);
});
module.exports = router;
React component on the client:
import React, { useEffect } from 'react';
import axios from 'axios';
const First = () => {
useEffect(() => {
axios({
url: 'http://localhost:5000/excel',
method: 'GET',
responseType: 'blob',
}).then(res => {
const url = window.URL.createObjectURL(new Blob([res.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'data.xlsx');
document.body.appendChild(link);
link.click();
});
}, []);
return (
<div>
<h3>First page</h3>
<hr className="gold" />
</div>
);
};
export default First;
Regards.