I am building an app using node.js that needs to allow the user to download a .csv file.
The problem - the app does not send a file to the client as an attachment when the user clicks a button. HOWEVER, if the client goes directly to the API link, the file will download. E.g. - if the user goes to localhost:3000/api/exportmetric
, the a file will be sent to the client as an attachment. But if that route is hit as an AJAX request, nothing happens.
User flow:
1) User clicks a button
2) App makes AJAX GET request to server
3) Server retrieves data from a database
4) Server parses the data into a .csv file
5) Server sends file back to the client to download as an attachment.
My code:
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);
});
});