【发布时间】:2016-05-11 21:30:21
【问题描述】:
我正在使用 node.js 构建一个需要允许用户下载 .csv 文件的应用程序。
问题 - 当用户单击按钮时,应用程序不会将文件作为附件发送到客户端。但是,如果客户端直接访问 API 链接,则会下载该文件。例如。 - 如果用户转到localhost:3000/api/exportmetric,文件将作为附件发送给客户端。但是,如果该路由作为 AJAX 请求被命中,则不会发生任何事情。
用户流量:
1) 用户点击按钮
2) 应用向服务器发出 AJAX GET 请求
3) 服务器从数据库中检索数据
4) 服务器将数据解析成 .csv 文件
5) 服务器将文件发送回客户端以作为附件下载。
我的代码:
client.js
$("#export_velocity").click(function(e) {
console.log('export to velocity hit');
$.ajax({
url: 'http://localhost:3001/api/exportmetric',
type: 'GET',
success: function(response) {
console.log(response);
},
error: function(a, b, c) {
console.log(a);
console.log(b);
console.log(c);
}
});
});
server.js
router.get('/api/exportmetric', function(req, res) {
console.log('export metric hit');
var fields = ['first_name', 'last_name', 'age'];
var fieldNames = ['First Name', 'Last Name', 'Age??'];
var people = [
{
"first_name": "George",
"last_name": "Lopez",
"age": "31"
}, {
"first_name": "John",
"last_name": "Doe",
"age": "15"
}, {
"first_name": "Jenna",
"last_name": "Grassley",
"age": "44"
}
];
json2csv({ data: people, fields: fields, fieldNames: fieldNames }, function(err, csv) {
res.setHeader('Content-disposition', 'attachment; filename=file.csv');
res.set('Content-Type', 'text/csv');
console.log(csv)
res.status(200).send(csv);
});
});
【问题讨论】:
-
不使用 ajax。
<a href="http://localhost:3001/api/exportmetric">Download CSV!</a>别想太多了! -
对,但最终我将需要使用 AJAX 将数据发送到我的服务器以查询需要下载到 csv 文件中的某些类型的数据
-
您也可以使用 GET 和锚标记发送数据。不少于 ajax 允许的数据。
-
使用ajax的问题是不能直接下载ajax请求的响应。相反,您必须将其设置为一个两步过程,服务器存储文件并将 URL 发送到客户端以供下载,然后在下载完成后将其删除,这有点复杂。到那时,再次删除 ajax 并进行表单发布或访问 iframe 会更容易
-
我明白了,你能澄清一下
send data with GET and an anchor tag吗?或者指出我在哪里可以找到有关它的更多信息?