I am creating an application using node.js, which should allow the user to download the CSV file.
Problem - The application does not send the file to the client as an attachment when the user clicks the button. HOWEVER, if the client goes directly to the API link, the file will be downloaded. For example. - if the user goes to localhost:3000/api/exportmetric, the file will be sent to the client as an attachment. But if this route gets as an AJAX request, nothing happens.
User stream:
1) The user presses the button
2) The application makes an AJAX GET request to the server
3) The server retrieves data from the database
4) The server analyzes the data in a CSV file
5) The server sends the file back to the client for download as an attachment.
My code is:
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);
});
});