2

I am using Express with Node.

I am attempting to send a PDF file as a response.

This PDF file is first retrieved from another server using http.request() after which I wish to pipe it to the response.

That is, when the browser makes a request for the route '/PDF, I carry out the following:

app.get('/PDF', function (req, res) { var options = { host: host, path: path, method: 'GET', headers: {} };

var requesting = http.request(options, function (response) {
    var body = '';

    response.setEncoding('utf8');

    response.on('data', function (chunk) {
        body += chunk;
    });
    response.on('end', function () {
        var data = null;
        if (body) {
            try {
                data = JSON.parse(body);
            }
            catch (err) {
                data = body;
            }
        }

        res.sendfile(data);
    });
});

requesting.end();

});

However, an error is thrown at res.sendfile(data):

Error: Bad Request
    at SendStream.error (redacted/send.js:145:16)
    at SendStream.pipe (redacted/send.js:298:31)
    at ServerResponse.res.sendfile (redacted/response.js:339:8)
    at IncomingMessage.<anonymous> (redacted/api.js:289:17)
    at IncomingMessage.EventEmitter.emit (events.js:117:20)
    at _stream_readable.js:920:16
    at process._tickCallback (node.js:415:13)

How do I pass the HTTP GET request body (with content type 'application/pdf') to the browser?

callmekatootie
  • 10,989
  • 15
  • 69
  • 104
  • The first argument passed to `res.sendfile()` function should be a file path. – bnuhero Mar 25 '14 at 08:41
  • You can set the response header with `Content-Type: application/pdf` and pipe the data stream to the response object. Reference: http://stackoverflow.com/questions/17622265/nodejs-expressjs-send-response-of-large-amount-of-data-in-1-stream – bnuhero Mar 25 '14 at 08:53
  • Thanks. I realized that too. I ended up having to store the PDF file after the GET request (using this answer: http://stackoverflow.com/a/19953735/2104976 And then I proceeded to read the PDF file and send it as response using this: http://stackoverflow.com/q/11598274/2104976 – callmekatootie Mar 25 '14 at 10:00

0 Answers0