2

I have a node app using koa, and trying to retrieve remote pdf, and return it as a response of my koa request. Here is the code:

router.get('/pdf', function *() {
    const url = 'http://example.com/pdf'
    const res = yield request(url)
    this.status = res.statusCode
    Object.keys(res.headers).forEach(key => {
      this.set(key, res.headers[key])
    })
    this.body = res.body
})

I get the pdf with blank page, but it should have content in it. Does anyone have an idea what could be the solution?

mirna
  • 23
  • 3

1 Answers1

4

This was a little tricky to figure out. I found out that the stream package's PassThrough function had to be used. The code below streams an external PDF to the /pdf route and it will be openable in a browser.

const Koa = require('koa');
const Router = require('koa-router');

const app = new Koa();
const router = new Router();

// Source: http://koajs.com/#stream
const PassThrough = require('stream').PassThrough;
const request = require('request');

router.get('/pdf', (ctx) => {
  const url = 'https://collegereadiness.collegeboard.org/pdf/sat-practice-test-8.pdf';
  ctx.set('Content-Type', 'application/pdf');
  ctx.body = request(url).pipe(PassThrough());
});

app
  .use(router.routes());

app.listen(3000);
SomeGuyOnAComputer
  • 5,414
  • 6
  • 40
  • 72
  • 1
    Thanks, this works. I solved it by passing encoding: null parameter to the request options, I figured the issue was with the encoding, and found solution here: https://stackoverflow.com/questions/14855015/getting-binary-content-in-node-js-using-request?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – mirna Apr 09 '18 at 09:43