我使用节点将一些数据发布到外部服务,该服务应该将PDF送回保存,但我认为这两个部分都做得不对(我是节点新手)。我在论坛上看过,尝试过十几种方法,但我要么得到一个空白的PDF,要么一个坏的。下面是我为请求使用的代码(万一我做错了),尽管我尝试使用postman调用该服务,并得到一个保存文件的提示,而且它可以工作,所以它并不一定是外部服务。
var x = {//data to be sent}
var options = {
method: 'POST',
uri: '//link',
form: x,
headers: {
"Content-Type": "application/json",
'Authorization': 'Basic ' + new Buffer("user:pass").toString('base64')
}
};
request(options, function(error, response, body) {
//How to properly get the stream and save it as a valid PDF?
//I tried fs.witeFile, createWriteStream, pipe, and a bunch
//of other ways without luck.
});以下是我从外部服务得到的响应:
{
"statusCode": 200,
"body": "%PDF-1.4\n1 0 obj\n<<\n/Title (��)\n/Creato..{//very long response}..",
"headers": {
"x-powered-by": "Express",
"access-control-allow-origin": "*",
"vary": "Origin",
"connection": "close",
"content-type": "application/pdf",
"content-disposition": "inline; filename=\"report.pdf\"",
"file-extension": "pdf",
"number-of-pages": "1",
"x-xss-protection": "0",
"set-cookie": [
"session=_O2T27N......"
],
"date": "Thu, 21 Jan 2016 23:13:16 GMT",
"transfer-encoding": "chunked"
},
"request": {
"uri": {
"protocol": "https:",
"slashes": true,
"auth": null,
"host": "xxxxx.net",
"port": 443,
"hostname": "xxxxx.net",
"hash": null,
"search": null,
"query": null,
"pathname": "/api/report",
"path": "/api/report",
"href": "https://xxxxx.net/api/report"
},
"method": "POST",
"headers": {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic aXRA......",
"content-length": 129
}
}
}如果有人知道如何正确获取和保存该文件,将不胜感激。
发布于 2016-01-22 20:39:27
我希望您使用的是请求模块,它返回一个流。您需要做的唯一一件事就是将这个流输送到一个文件中。这是通过以下方式完成的
request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))然后,完整的示例如下所示:
var options = {
method: 'POST',
body: JSON.stringify({ template: { recipe: 'phantom-pdf', engine: 'handlebars', content: 'Hello world'}}),
uri: 'http://localhost:3000/api/report',
headers: {
"Content-Type": "application/json",
'Authorization': 'Basic ' + new Buffer("admin:password").toString('base64')
}
};
request(options, function(error, response, body) {
}).pipe(fs.createWriteStream("report.pdf"))您还可以检查jsreport-client,这使得远程报表呈现在node.js中更容易。
https://stackoverflow.com/questions/34936227
复制相似问题