如何从客户端后端下载生成的csv文件
我正在使用 ejs 和节点。按下按钮后,我将生成一个包含一些信息的 csv 文件。我想在客户端下载它。这是我正在尝试的代码,但它不起作用。
app.post('/', async(req, res) => {
console.log('triggerd');
console.log('req', req.body);
const url= req.body.url;
await scrapeData(url);
const file = `${__dirname}/companies1.csv`;
res.download(file); // Set disposition and send it.
res.redirect('/')
})
如果可能的话请帮忙。
I am using ejs and node. On a button press there I am generating a csv file containing some information. I want to download that in the client side. This is the code I am trying but its not working.
app.post('/', async(req, res) => {
console.log('triggerd');
console.log('req', req.body);
const url= req.body.url;
await scrapeData(url);
const file = `${__dirname}/companies1.csv`;
res.download(file); // Set disposition and send it.
res.redirect('/')
})
Please help if possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,如果您想从后端检索数据,您应该使用 get 请求而不是 post 请求。 post请求是从前到后发送数据,get请求是从后到后发送数据。
其次,如果您想从 Node.js 服务器发送文件,您可以使用以下方法:
这将返回文件的二进制值,您必须使用 a 将其转换为字符串,然后转换为文件像这样的函数(这个是在 Angular/TypeScript 中,我真的不知道它是否适用于 ejs):
使用此解决方案,您可以在前端代码中使用 csv 文件,但它不会保存在客户端计算机中
Firstly, if you want to retrieve data from your backend, you should use a get request and not a post request. Post requests are for sending data from front to back, and get requests for sending data from back to end.
Secondly, if you want to send a file from your node.js server, you can use the following method :
This will return a binary value of your file, that you will have to convert to a string and then to a file, using a function such as this (this one is in angular/typescript, I don't really know if it applies to ejs) :
With this solution, you can use the csv file in your front code, but it is not saved in the client's computer