Tikkes Tikkes - 4 months ago 70
Node.js Question

NodeJS - prompt download CSV file

I'm trying to get - after some promises have been executed - a CSV result back together with a status reponse having details.

The response does get me the data for the CSV but I cannot seem to get the browser to download this data into a CSV file.

router.post('/getSalesOrders', function (request, response) {
var data = request.body;
salesOrderActions.retrieveSalesOrders(data) //
.then(function (result) {
response.setHeader('Content-disposition', 'attachment; filename=testing.csv');
response.set('Content-Type', 'text/csv');
response.json(result[0].message).send(result[0].file);
})
.catch(function (err) {
console.log(err);
if (err.statusCode) {
response.json(err);
}
else {
var error = output.getCriticalErrorResult(c.titles.SERVICE_CRITICAL_ERROR, c.messages.UNKNOWN_ERROR, err.message);
response.json(error);
}
});
});


My result object gets created in the
salesOrderActions
:

I am here using npm package json2csv

var fields = ['id',.....];
var csv = csvParser({ data: unmatchedLines, fields: fields });

return {
file: csv,
message:
output.getSuccessResult(
titles.SALES_ORDER_SUCCESS_RETRIEVAL,
salesDataForModel.identifier
)
}


My response to the browser is as follows:
enter image description here
enter image description here

So my message isn't sent it seems and I do get the CSV data but not as a file to download.
How can I manage that?

As a sidenote maybe, my front-end is
React


EDIT

Response with octed headers:

enter image description here
enter image description here

Answer

So actually it turns out it is because I'm doing an Ajax request which doesn't - by default - prompt the browser to download any files.

What I did in the end:

router.post('/getSalesOrders', function (request, response) {
    var data = request.body;
    salesOrderActions.retrieveSalesOrders(data)
        .then(function (result) {
            response.json(result);
        })
        .catch(function (err) {
            //...
        });
});

And then in my front-end, when receiving the result:

salesOrderService.retrieveSalesOrderData()
.then(function (result) {
    self.convertAndDownloadCsv(result.unmatchedLines);
});

convertAndDownloadCsv: function (data) {
    if (data && data.length > 0) {
        var csvData = csvProcessor({ //using csv2json node js package
            data: data,
            quotes: '',
            del: ';'
        });
        var filename = "unmatchedLinesFromSalesOrders.csv";
        var blob = new Blob([csvData], { type: 'text/csv;charset=utf-8;' });
        if (navigator.msSaveBlob) { // IE 10+
            navigator.msSaveBlob(blob, filename);
        } else {
            var link = document.createElement("a");
            if (link.download !== undefined) { // feature detection
                // Browsers that support HTML5 download attribute
                var url = URL.createObjectURL(blob);
                link.setAttribute("href", url);
                link.setAttribute("download", filename);
                link.style.visibility = 'hidden';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }
        }
    }
}

More info can be found here

Comments