我一直在努力這一段時間,似乎無法找到答案,我正在開發一個網站與預算選項,我從客戶端發送一個對象到服務器,並且該服務器正在使用PDFKit創建預算的PDF版本,一旦它被創建,我希望實際上將該PDF發送回客戶端並觸發下載,這是我的做res.download(NodeJS)沒有觸發在瀏覽器上下載
客戶端代碼:
let data = {
nombre: this.state.name,
email: this.state.email,
telefono: this.state.phone,
carrito: this.props.budget.cart,
subTotal: this.props.budget.subTotal,
IVA: this.props.budget.tax,
total: this.props.budget.subTotal + this.props.budget.tax
}
axios({
method: 'post',
url: 'http://localhost:1337/api/budget',
data: data
})
.then((response) => {
console.log('This is the response', response);
window.open('/download')
})
.catch((error) => {
alert(error);
})
,使數據轉移到我的服務器端代碼完美,它看起來像這樣
const pdf = require('pdfkit');
const fs = require('fs');
const path = require('path');
exports.makePDFBudget = (req, res) => {
let myDoc = new pdf;
myDoc.pipe(fs.createWriteStream(`PDFkit/budget.pdf`));
myDoc.font('Times-Roman')
.fontSize(12)
.text(`${req.body.name} ${req.body.phone} ${req.body.email} ${req.body.cart} ${req.body.subTotal} ${req.body.total} ${req.body.tax}`);
myDoc.end()
}
這就是創建我的PDF,我現在想要的是,一旦它被創建並且響應被髮送回客戶端,客戶端將打開一個新的窗口,該URL設置爲下載PDF,但這並不是因爲某些原因而發生的,它打開了新窗口,但下載從未啓動,並且它絕對沒有錯誤我是我的節點控制檯或瀏覽器控制檯 這是我如何將文件發送到客戶端
const fs = require('fs');
const path = require('path');
exports.downloadPDFBudget = (req, res) => {
res.download(__dirname + 'budget.pdf', 'budget.pdf');
}
這就是我的服務器索引看起來像
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
const api = express.Router();
const { makePDFBudget } = require('./PDFkit/makePDFBudget.js');
const { downloadPDFBudget } = require('./PDFkit/downloadPDFBudget.js')
app.use(express.static(__dirname + '/../public'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json({extended: true}));
api.route('/budget')
.post(makePDFBudget)
api.route('/download')
.get(downloadPDFBudget)
app.use('/api', api);
const port = 1337;
app.listen(port);
console.log('Listening on port ', port);
module.exports = app;
恭喜 – galkin