I need to download a pdf from an endpoint I receive from an external service, store the pdf in my database and send it back to the browser (or whoever is calling the API on my system). For some reasons I can't understand if I put the service's URL directly on the browser it opens the pdf correctly, but if I run this code
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);
by calling localhost:9008/
from the browser I only get 2 blank pages. I kind of tried them all changing all possible configurations and encodings but so far I only got blank pages.
In case you need more informations please ask.
Pleae change
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);
});
to
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
So, I finally found how to do it:
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');
});
This could be super easy as
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);
});
You don't have to store data on the server this way.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.