Pedro Guilherme
Pedro Guilherme

Reputation: 31

How can I send pdf to client from API request

I'm sending a request to an API that returns pdf files. I've tried res.send(data) but it doesn't work, and just returns a blank PDF file.

rp("URI")
    .then(data =>{
        res.contentType("application/pdf")
        res.send(data)
    })
    .catch(e =>{
        console.log(e)
    })

Upvotes: 2

Views: 5552

Answers (1)

molamk
molamk

Reputation: 4116

  • Send is used for common HTTP response like JSON, XML, etc..
  • To send files you need to call res.sendFile with the filePath and its parameters

It looks like this

app.get('/file/:name', function (req, res, next) {

  var options = {
    root: __dirname + '/public/',
    dotfiles: 'deny',
    headers: {
        'x-timestamp': Date.now(),
        'x-sent': true
    }
  };

  var fileName = req.params.name;
  res.sendFile(fileName, options, function (err) {
    if (err) {
      next(err);
    } else {
      console.log('Sent:', fileName);
    }
  });

});

Upvotes: 2

Related Questions