I am using ExpressJS to develop a web app.
There is a Create button on the page. What I want to achieve is, when the button is clicked, it sends a Post/Get request to the server side, and the server side then triggers a process to generate a CSV file and send it back to the client side for download.
I am thinking of using json2csv.
Client side:
$.ajax({
            type: "POST",
            url: "/incidents/createTable",
            success: function() {
                // HOW TO GET THE RETURNED DATA TO A DOWNLOADABLE FILE?
            }
        });
Server side and incidents router (the code snippet that follows was copied from the json2csv official npmjs page):
const { AsyncParser } = require('json2csv');
// THIS FUNCTION SHOULD GENERATE A CSV FILE IN MEMORY
router.post("/createTable", async function(req, res, next) {
    console.log("flag 1");  // For flagging
    const fields = ['field1', 'field2', 'field3'];
    const opts = { fields };
    const transformOpts = { highWaterMark: 8192 };
    const asyncParser = new AsyncParser(opts, transformOpts);
    console.log("flag 2");  // For flagging
    let csv = '';
    asyncParser.processor
    .on('data', chunk => (csv += chunk.toString()))
    .on('end', () => res.send(csv))
    .on('error', err => console.error(err));
});
When I ran the web app and clicked the Create button, the server hung there, it passed "flag 2" and never went pass the asyncParser.processor. On the client side, the POST request was also hung there and with no status code.
 
    