【发布时间】:2020-12-21 18:39:43
【问题描述】:
我的节点后端有以下方法生成pdf并保存在服务器目录data/invoices/中。
exports.generateInvoice = async(req, res, next) => {
const orderId = req.params.orderId;
try {
const order = await Order.findById(orderId);
const data = await order.populate("user.userId").execPopulate();
if (!order){
const error = new Error("Order not found");
error.statusCode = 404;
throw error;
}
if (data.user.userId._id.toString() !== req.userId.toString()) {
return next(new Error("Unauthorized"));
}
const invoiceName = "invoice-" + orderId + ".pdf";
const invoicePath = path.join("data", "invoices", invoiceName);
let doc = new PDFDocument({ size: "A4", margin: 50 });
generateHeader(doc);
generateCustomerInformation(doc, data);
generateInvoiceTable(doc, data);
generateFooter(doc);
doc.end();
doc.pipe(fs.createWriteStream(invoicePath));
res.status(200).json({path: 'http://localhost:8080/'+invoicePath});
}catch (e){
if (!e.statusCode) {
e.statusCode = 500;
next(e);
}
}
}
generateHeader(doc);
generateCustomerInformation(doc, data);
generateInvoiceTable(doc, data);
generateFooter(doc);
只是我创建的辅助方法。
这是我的前端 vue 方法,触发上述方法生成发票 pdf。
methods: {
async getInvoice(orderId){
console.log("click");
const res = await this.$axios.get('product/get-invoice/'+ orderId, {
headers: {
Authorization: 'Bearer ' + this.userData.userToken
}
});
console.log(res);
}
},
如何下载最近创建的 pdf 文件?
【问题讨论】:
标签: javascript node.js vue.js vuejs2 axios