res.download(NodeJS)不会在浏览器上触发下载

时间:2017-07-03 20:11:37

标签: node.js reactjs pdf download axios

我一直在努力解决这个问题似乎无法找到答案,我正在开发一个带有预算选项的网站,我正在从客户端向服务器和服务器发送一个对象正在使用PDFKit创建预算的PDF版本,一旦创建我希望实际将该PDF发送回客户端并触发下载,这就是我所做的

客户端代码:

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为“/ download”,设置为下载该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;

2 个答案:

答案 0 :(得分:0)

  1. 我想这里的主要问题是:

    res.download(__ dirname +' budget.jpg',' budget.pdf');

    制作正确的文件名。你的文件是pdf,而不是jpg。

  2. 在此代码res.end(Buffer.from('budget.pdf'))处发送字符串,而不是文件内容。但是像您要发送文件的标题。

  3. 最后一个。您的应用程序设计与您一样只有一个用户。你可以将userId添加到文件名吗?或者使用DB存储数据并根据请求生成pdf,而无需将文件存储到文件系统。

答案 1 :(得分:0)

我刚刚解决了它,我运行客户端的端口显然与我运行服务器的端口不同,所以我不得不打开一个窗口到我的服务器端口来触发下载,我意识到这是因为我抛出了一个控制台日志,该函数应该执行它没有显示的res.download。谢谢!