You must have tried with downloading data in CSV using GET request from UI and used Node.js as backend.

How are you going to download the same data in csv using POST request from UI ? ( there’s some scenario where you need to consume some data from UI and rest from backend code )

Topics covered:

1. Download CSV using GET request using node.js NPM

2. Download CSV using POST request

Download CSV using GET request

If you are using Hapi.js Framework


json2csv = require('json2csv');

json2csv({data: request.payload,  
        fields: ['productId', 'extProductId', 'tenantId', 
                 'supplierId', 'statusId', 'mfgProductId', 
                 'mfgProductName', 'manufacturerId', 'manufacturerName'],
        fieldNames: ['productId', 'extProductId', 'tenantId', 'supplierId', 
                     'statusId', 'mfgProductId', 'mfgProductName', 'manufacturerId', 
                     'manufacturerName']},
        function(err, csv) {
                if (err) console.log(err);
                return reply(csv)
                .header('Content-Type', 'application/octet-stream')
                .header('content-disposition','attachment; filename=CronjReport.csv;');
        });

If you are using Express.js Framework


json2csv = require('json2csv');

json2csv({data: request.payload,  
        fields: ['productId', 'extProductId', 'tenantId', 
                 'supplierId', 'statusId', 'mfgProductId', 
                 'mfgProductName', 'manufacturerId', 'manufacturerName'],
        fieldNames: ['productId', 'extProductId', 'tenantId', 'supplierId', 
                     'statusId', 'mfgProductId', 'mfgProductName', 'manufacturerId', 
                     'manufacturerName']},
        function(err, csv) {
                if (err) console.log(err);
                response.setHeader('Content-Type', 'application/octet-stream');
                response.setHeader("Content-Disposition", 'attachment; filename=CronjReport.csv;');
                response.end(csv, 'binary');
        });

Download CSV using POST request

You only need to handle differently from Angular side.


$http.post('/exportProduct',searchdata)
     .success(function(data, status, headers, config) {
         var element = angular.element('');
	 element.attr({
	   href: 'data:attachment/csv;charset=utf-8,' + encodeURI(data),
	   target: '_blank',
	   download: 'name.csv'
	 })[0].click();
       })
       .error(function(data, status, headers, config) {
			   
	});

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.