2

I want to download pdf file by fetching from Flask db.

React code:

downloadReport(idx) {
    console.log(idx)
    fetch('/getDataReport', {
      method: 'post',
      headers: {'Content-Type':'application/json', 'Accept':'application/json', 'responseType':'arraybuffer'},
      body: JSON.stringify({id: idx}),
    }).then(res => res.json()).catch(error => {
      console.error('Error:', error);
  })
  .then(response => {
      console.log(response)
  }) 
  }

The above is triggered by onClick method, I get the id and put it in API body. When I give the id I want to make it download from db.

Flask code:

def getData():
   req = flask.request.get_json(force=True)
   id = req.get('id', None)
   report = Report.query.filter_by(id=id).first()
   return send_file(BytesIO(report.get_data()), attachment_filename=report.get_date()+'-report.pdf', as_attachment=True)

When I click download, Post request working fine actually. But I get "index.js:1437 Error: SyntaxError: Unexpected token % in JSON at position 0" error and my response is undefined. I couldn't solve it. Hope someone can help. Thank you in advance.

reactjs

B.Y.
  • 63
  • 1
  • 6

1 Answers1

0

I'd start by looking at the line where you're attempting to deserialize the response as JSON:

.then(res => res.json())

Typically when fetching a file from an endpoint, the response is handled as a blob:

.then(res => res.blob()).then((blob) => { // do what you need to do })

blob() MDN Documentation

Once you've gotten the file, then you'll need a mechanism to force the browser to download the file. There are a few NPM packages that can help with this such as downloadjs or you can roll your own.

Another StackOverflow post on the same topic

Steve
  • 11,596
  • 7
  • 39
  • 53