Ahmed Haque
Ahmed Haque

Reputation: 7534

POST Request creates file, followed by GET Request to download

Trying to do something seemingly basic.

I'd like to create a POST request through which I'll be sending JSONs. These JSONs will be created into files, which I'd like to return to the user via download.

The use case for this is that I'm building an application which takes a form and converts it into a JSON for upload to a MongoDB database. Users can load these JSONs into the application to re-load their old records as templates.

This is how I'm approaching it as of now:

// Download JSON Previews
var jsondownload = {};

// Grabs the JSON from POST request
app.post('/api/download', function(req, res, next){
    jsondownload = {};
    var json = req.body;
    jsondownload = json;
    res.json(jsondownload);
    next();
});

// Immediately downloads the JSON thereafter
app.get('/api/download', function(req, res){
    res.set({"Content-Disposition":"attachment; filename='test.json'"});
    res.send(jsondownload);
});

What's the right way to do this?

Upvotes: 0

Views: 99

Answers (1)

mscdex
mscdex

Reputation: 106706

There is no one "right" way to do it, but a few solutions include:

  1. Remove the GET route handler (and the jsondownload variable) completely and just respond immediately with the Content-Disposition set appropriately. This is the better of the 3 because it reduces code and keeps things simple.

  2. Use a simple redirect in your POST route handler. Instead of responding with the JSON immediately, you would do res.redirect('/api/download').

  3. Do more or less what currently doing, but move the logic (the res.set() and res.send()) to a separate function that gets called from both route handlers.

Upvotes: 1

Related Questions