我正在使用node将一些数据发布到外部服务,该服务应该将我发回PDF以保存,但我认为我没有正确执行任何一部分(我是node的新手)。我在论坛上查看并尝试了十几种方法,但我要么得到空白的 PDF,要么得到一个损坏的 PDF。这是我用于请求的代码(以防我做错了),尽管我尝试使用邮递员调用服务并收到保存文件的提示,并且它可以工作,所以它肯定不是外部服务。
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.4n1 0 objn<<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
}
}
}
如果有人知道如何正确获取和保存此文件,将不胜感激。
我希望您正在使用返回流的请求模块。您唯一需要做的就是将此流传送到文件中。这是通过以下方式完成的
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中的远程报告呈现更容易。