John Bull
John Bull

Reputation: 103

CSV File downloads from Node Express server

I have an API backend with Node and Express. I am trying to take some filtered data from the frontend and create a CSV file and download it for the user. I have been using json2csv. I am able to create the data file correctly and when I use that file in my express route I download a file that just says undefined. At first, I thought it was an asynchronous issue, but after using a setTimeout as a test to see if that was an issue I still get the undefined data file. Console logging the "csvData" shows the correct data.

Express route to download the file.

app.post('/api/downloads/filtered', (req, res) => {
    let fields = [];
    fields = Object.keys(req.body[0])
    const filteredData = req.body;
    const json2csvParser = new json2csv({fields: fields});
    const csvData = json2csvParser.parse(filteredData);
    console.log(csvData)
    fs.writeFile('./report.csv', csvData, (err) => {
        if (err) {
            console.log(err);
        }
        else {
            console.log('created report.csv');
            res.download('./report.csv');
        }
    })
})

I'm using Vue on the frontend, I get the file when clicking a button not sure if that is something I should include.

Upvotes: 0

Views: 356

Answers (1)

John Bull
John Bull

Reputation: 103

I ended up figuring out my issue. I found that downloading in a post request didn't seem to be possible. I needed a get request. Since the data for the file came in the request body I ended up keeping the post request to create the file and creating a separate get request to download the file this seemed to work fine but didn't find it documented anywhere so I wasn't sure if a better way exists.

app.post('/api/downloads/filtered', (req, res) => {
    console.log(req.body)
    let fields = [];
    fields = Object.keys(req.body[0])
    const filteredData = req.body;

    const json2csvParser = new json2csv({fields: fields});
    const csvData = json2csvParser.parse(filteredData);
    console.log(csvData)
    fs.writeFile('./report.csv', csvData, (err) => {
        if (err) {
            console.log(err);
        }
        else {
            console.log('created report.csv');
        }
    })
})

app.get('/api/downloads/filtered', (req, res) => {
    setTimeout(() => {res.download('./report.csv')}, 1000)
})

Upvotes: 1

Related Questions