Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Post request that returns a download file

I am sending data to my server that creates a pdf file based from the request, which is being created fine but I cant get the file to be sent back to the client. I am using React to submit the form

handleSubmit(event) {
event.preventDefault();
var body = {
  id: this.state.id,
  text: this.state.text
}
fetch('http://localhost:5000/pdf', {
            method: 'POST',
            body: JSON.stringify(body),
            headers: {
                'Content-Type': 'application/json'
            },
        }).then(function(file) {
          window.open(file.url);
        });
}

Its opening http://localhost:5000/pdf, but since I don't have a GET route for it, nothing gets download. This is my POST route

router.post('/pdf', async function(req, res) {
  var makePdf = require('./file-create/pdf.js');
  makePdf(req, res);
});

and the file is being returned as pdfDoc.pipe(res);

I cant just use a GET route because I can't get data sent in with that way, how can I get this file to get sent to the client?

like image 677
qaakmnd Avatar asked Aug 23 '18 20:08

qaakmnd


1 Answers

You're calling a GET request when you're using window.open. This will open the url in a new tab with the URL. This won't work when you have changed it from GET to POST.

To get around this, you can use downloadjs (https://www.npmjs.com/package/downloadjs) to allow you to download the blob that is returned from the server.

I've included some example code below. This includes the index.html file with the fetch request and the server.js for returning a simple pdf.

index.html

var body = {
  id: 1,
  text: 'hello world',
};

fetch('/download', {
  method: 'POST',
  body: JSON.stringify(body),
  headers: {
    'Content-Type': 'application/json'
  },
}).then(function(resp) {
  return resp.blob();
}).then(function(blob) {
  return download(blob, "CUSTOM_NAME.pdf");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/downloadjs/1.4.8/download.min.js"></script>

server.js

var express = require('express');
var app = express();

app.post('/download', function(req, res){
    res.download('./make-file/whatever.pdf');
});

app.listen(3000);
like image 96
Win Avatar answered Nov 09 '22 01:11

Win