0

I have a node application which needs to do the following:

  1. POST a request with some HTML in the body to a PHP API that returns a PDF
  2. Return the PDF directly to the browser

I am trying something like this with node-fetch:

const response = await fetch('https://php-pdf-api.test', {
  method: 'post',
  body: JSON.stringify({
    'html': '<div>Hello</div>'
  }),
  header: {'Content-Type': 'application/json'}
})

const data = await response.text()
res.setHeader("Content-Type","application/pdf");
res.send(data)

Which results in a jumbled file:

jumbled PDF output

I imagine something is happening to the encoding when using response.text(), how can I pass this data on to the user's browser properly?

waffl
  • 5,179
  • 10
  • 73
  • 123

1 Answers1

0

Ah, with the help of https://stackoverflow.com/a/44291305/436014

I realized I don't even need node-fetch and could accomplish this directly with request like so:

request.post({
  url: 'https://php-pdf-api.test',
  body: JSON.stringify({
    'html': '<div>Hello</div>'
   }),
  json: true
}).pipe(res)
waffl
  • 5,179
  • 10
  • 73
  • 123
  • I know you solved using `request` but since it is deprecated did you manage to do the same using `fetch`? – afe Aug 04 '23 at 10:16