【发布时间】:2017-11-17 15:33:15
【问题描述】:
我目前正在我的 Koa.js 层中实现一些功能,当调用方法时会生成 PDF,然后作为下载文件返回给用户。我目前无法让它工作,也看不出原因。
我可以在我的 Chrome 网络选项卡中看到响应标头是正确的,但它没有打开,所以这让我怀疑响应的正文不正确,但我不明白为什么。
这是我的代码:
import Router from 'koa-router';
const PDFRouter = new Router();
import PDFDocument from 'pdfkit';
import PDFController from '../../../controllers/api/PDFController';
const PDFControllerInstance = new PDFController();
PDFRouter.post('/generate-pdf', async (ctx, next) => {
let doc = new PDFDocument();
const filename = 'claim';
ctx.response.set('Content-disposition', 'attachment; filename="' + filename + '"');
ctx.response.set('Content-type', 'application/pdf');
const PDFfile = ctx.res.pipe(doc);
doc.end();
ctx.body = PDFfile;
});
export default PDFRouter;
如您所见,我正在使用 PDFkit 库来生成 PDF。原始 PDF 代码在响应的正文中发送。这是请求、响应标头和正文。
Request URL:http://degould-login.dev/api/generate-pdf
Request Method:POST
Status Code:200 OK
Remote Address:127.0.0.1:80
Referrer Policy:no-referrer-when-downgrade
Response Headers
view source
Access-Control-Allow-Methods:GET,HEAD,PUT,POST,DELETE
Access-Control-Allow-Origin:http://degould-login.dev
Connection:keep-alive
Content-disposition:attachment; filename="claim"
Content-Type:application/pdf
Date:Fri, 17 Nov 2017 15:22:56 GMT
Server:nginx/1.10.3 (Ubuntu)
Transfer-Encoding:chunked
Request Headers
view source
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate
Accept-Language:en-GB,en-US;q=0.9,en;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Content-Length:11
content-type:text/plain
Cookie:XDEBUG_SESSION=XDEBUG_ECLIPSE
Host:degould-login.dev
Origin:http://degould-login.dev
Pragma:no-cache
Referer:http://degould-login.dev/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.89 Safari/537.36
下面是回复:
%PDF-1.3
%ÿÿÿÿ
5 0 obj
<<
/Type /Page
/Parent 1 0 R
/MediaBox [0 0 612 792]
/Contents 3 0 R
/Resources 4 0 R
>>
endobj
4 0 obj
<<
/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]
>>
endobj
6 0 obj
<<
/Producer (PDFKit)
/Creator (PDFKit)
/CreationDate (D:20171117152256Z)
>>
endobj
2 0 obj
<<
/Type /Catalog
/Pages 1 0 R
>>
endobj
1 0 obj
<<
/Type /Pages
/Count 1
/Kids [5 0 R]
>>
endobj
3 0 obj
<<
/Length 23
/Filter /FlateDecode
>>
stream
x3T0B]C ani¤ËI\
endstream
endobj
xref
0 7
0000000000 65535 f
0000000327 00000 n
0000000278 00000 n
0000000384 00000 n
0000000119 00000 n
0000000015 00000 n
0000000186 00000 n
trailer
<<
/Size 7
/Root 2 0 R
/Info 6 0 R
>>
startxref
478
%%EOF
这是我向 Node.JS (Koa) 层发出请求的前端服务方法
generatePDF(PDFContent: string): Observable<any> {
return this._http.post(this._config.API_URL + '/generate-pdf', PDFContent)
.map((response) => response.json);
}
谁能看到我在这里做错了什么或提供一些建议?我希望 PDF 文件自动下载到客户的计算机上。 谢谢
【问题讨论】:
-
这是在特定版本的 Chrome 中吗?
-
不,它是任何浏览器。
-
您是如何提出请求的?您是否有某种形式的提交,或者您是否手动发出 AJAX 请求?
-
我会将请求详细信息添加到我的原始问题中