我正在尝试从后端生成CSV文件,并将其提供给我的前端进行下载。
数据已经在前端,我将它作为JSON数据发送到后端,并在后端成功生成了CSV文件,但是当获取文件的请求时,我收到500状态错误,响应为import { Parser } from 'json2csv';
export default class AutomationController {
static async postReport(req, res) {
try {
const fields = ['email', 'fellowName'];
const report = req.body;
const json2csvParser = new Parser({ fields });
const csv = json2csvParser.parse(report);
const path = `downloads/Reports.csv`;
fs.writeFile(path, csv, (err) => {
if (err) {
throw err;
} else {
res.download(path);
}
});
} catch (e) {
}
}
static async getReport(req, res) {
try {
return res.status(200).sendFile(`downloads/Reports.csv`);
} catch (err) {
return res.status(500).json({ error: err.message });
}
}
}
}
前端叫做
Express API代码
router.get('/fetchReport', automationController.getReport);
router.post('/downloadReport', automationController.postReport);
后端路由
import axios from 'axios';
import { saveAs } from 'file-saver';
createAndDownloadPDF = () => {
const { automationData } = this.state;
axios.post('http://localhost:8000/api/v1/automations/downloadReport', automationData)
.then(() => axios.get('http://localhost:8000/api/v1/automations/fetchReport', { responseType: 'blob' }))
.then((res) => {
const csvBlob = new Blob([res.data], { type: 'text/csv' });
saveAs(csvBlob, 'report.csv');
});
};
反应前端
{{1}}