无法在node.js中代理PDF文件

时间:2015-06-18 10:02:11

标签: javascript node.js http pdf proxy

我需要从外部服务接收的端点下载pdf,将pdf存储在我的数据库中并将其发送回浏览器(或者在我的系统上调用API的人)。 由于某些原因,我无法理解,如果我将服务的URL直接放在浏览器上,它会正确打开pdf,但如果我运行此代码

var express = require('express');
var request = require('request');

var app = express();
var _PORT = 9008;

console.log("starting server on port " + _PORT);

// will return an unordered list of all items.
app.get('/', function(req, res) {
    console.log("Proxying stuff");

    var get_options = {
        'rejectUnauthorized': false,
        'url': 'http://www.urartuuniversity.com/content_images/pdf-sample.pdf',
        'method': 'GET'
    };

    request(get_options, function(err, get_resp, body){
        if(err){
            console.log(err.message);
            res.json({error: err})
        }

        console.log('data received from service:' + body.length);

        res.type('application/pdf');
        res.end(body);
    });
});

app.listen(_PORT);

从浏览器调用localhost:9008/我只得到2个空白页。我尝试了所有可能的配置和编码,但到目前为止我只有空白页。

如果您需要更多信息,请询问。

3 个答案:

答案 0 :(得分:0)

请求改变

var get_options = {
        'rejectUnauthorized': false,
        'url': 'http://www.urartuuniversity.com/content_images/pdf-sample.pdf',
        'method': 'GET'
    };

    request(get_options, function(err, get_resp, body){
        if(err){
            console.log(err.message);
            res.json({error: err})
        }

        console.log('data received from service:' + body.length);

        res.type('application/pdf');
        res.end(body);
    });

request
  .get('http://www.urartuuniversity.com/content_images/pdf-sample.pdf')
  .on('response', function(response) {
    console.log(response.statusCode) 
    console.log(response.headers['content-type'])
  })
  .on('end', function(){
     // store pdf into DB here.
     fs.createReadStream('pdf-sample.pdf').pipe(res); // send the pdf to client
  })
  .pipe(fs.createWriteStream('pdf-sample.pdf')) //store the pdf in your server

答案 1 :(得分:0)

所以,我终于找到了如何做到这一点:

request
    .get('http://www.urartuuniversity.com/content_images/pdf-sample.pdf')
    .on('response', function(response) {

        var chunks = [];
        response.on('data', function(chunk){
            chunks.push(chunk);
        });

        response.on('end', function(){
            var finalData = new Buffer.concat(chunks);
            myDatabase.store(finalData);

            res.type('application/pdf');
            res.end(finalData, 'binary');
        });

答案 2 :(得分:0)

这可能非常简单

app.use('/pdf', (req, res) => {
  let url = 'http://www.urartuuniversity.com/content_images/pdf-sample.pdf';
  let src = request(url);
  req.pipe(src).pipe(res);
});

您不必以这种方式在服务器上存储数据。