In memory JSON to .json file browser download not working

Viewed 25

I am attempting to update a record and then receive a JSON file back in the clientside. I make the initial request with Axios. There is no file just the in memory JSON.

It gets to the express backend PUT route, updates the record, but does NOT initiate a file download. The data is sent as JSON in the response to the clientside. I am unaware what the issue is as I have set the headers and piped.

const dispenseProduct = async (req, res) => {
    try {
        const { productId } = req.body
        const product = await Products.findOne({ where: { productId } })
        const updatedProduct = await product.update({ currentInventory: --product.currentInventory })
        
        const readStream = new stream.PassThrough()
        readStream.end(Buffer.from(JSON.stringify(updatedProduct)))
        res.setHeader('Content-Disposition',`attachment; filename="${updatedProduct.name}.json"`)
        res.setHeader('Content-Type', 'text/json')
        readStream.pipe(res)
    } catch (err) {
        return catchErr(err, res)
    }
}
1 Answers

The issue was not related to the backend but rather the http request client on the frontend. There is an issue with Axios not supporting this behavior.

I had to manually rig it like so...

// extract filename from header
let filename = res.headers['content-disposition'].split('filename=')[1]
filename = filename.replaceAll('/', '')
filename = filename.replaceAll('"', '')

const link = document.createElement('a')
const temp = window.URL.createObjectURL(new Blob([JSON.stringify(res.data)]));

// trigger download
link.href = temp;
link.setAttribute('download', filename)
document.body.appendChild(link)
link.click();
   
Related