2

How to download a CSV file on a button click which sends a post request.

The post request has a huge response and hence, getting it from express to front end is not a feasible solution.

I want to get the data on express and create and send a csv to the front end which automatically downloads it.

Can somebody help?

divya biyani
  • 21
  • 1
  • 2
  • I think if you set the mime type to application/octet-stream it will force a download in the client – Tim Seguine May 30 '18 at 07:43
  • Possible duplicate of [Download a file from NodeJS Server using Express](https://stackoverflow.com/questions/7288814/download-a-file-from-nodejs-server-using-express) – madflow May 30 '18 at 07:51

2 Answers2

1

Basically to get something from server you should use GET instead on POST. Then set required response headers as below-

response.setContentType("text/csv"); response.setHeader("Content-Disposition", "attachment; filename=\"userDirectory.csv\"");

SanTech
  • 128
  • 2
  • 14
0

On the React side ,you can use an npm package react-csv.

for more information, you can visit: https://github.com/abdennour/react-csv .

The CSVDownload can be used to download the data from an API response, by passing data to CSVDownload component as props.

<CSVDownload data={this.props.data} /> assuming data is not empty

or if you want to download the data by Clicking a link , you can use

 <CSVLink data={this.props.data} filename="data.csv" > <span 
     className="icon-download download-csv-1" /></CSVLink>
Community
  • 1
  • 1
Erick
  • 1,098
  • 10
  • 21