将jsPDF生成的PDF发送到服务器

时间:2018-07-22 18:55:19

标签: javascript reactjs axios jspdf nodemailer

我正在用jsPDF生成PDF客户端。我需要使用Axios将其发送到Express服务器。最后,我需要使用Nodemailer通过电子邮件发送它。我哪里错了?

客户端代码

//doc creation ....
var res = doc.output('datauristring');   //this line!!!!
axios.post('/mailsender', res).then((res) => {
    if(res.status === 'ok') console.log("Yeah!");
    else console.log(":(");
});

服务器端代码

...

api_router.post('/mailsender', (req, res) => {
    mail.send(req.body, (res) => {
        res.status(200).json({"status": res ? 'ok' : 'error' });
    });
});

mail.js是

const nodemailer = require('nodemailer');

let transporter = nodemailer.createTransport({
    host: 'smtp.mail.yahoo.com',
    port: 465,
    secure: true,
    auth: {
        user: 'example@yahoo.it',
        pass: 'password'
    }
});


exports.send = function (data, callback) {
    let mailOptions = {
        from: '"My application" <example@myapp.com>',
        to: "receiverAddress",
        subject: "Attachment experiment",
        text: "My <3",
        attachments: [
            {
                filename: 'attachment.pdf',
                content: data,
                contentType: 'application/pdf',
                encoding: 'base64'    //this line!!!!
            }
        ]
    };

    transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
            return console.log(error);
            callback(false);
        }
        callback(true);
    });
}

一切正常,但如果我尝试打开收到邮件中的附件,则Preview表示文件已损坏。如果我尝试使用Google chrome或其他PDF阅读器打开它,也是如此。可能必须更改带有注释的两行。谢谢您的关注!

1 个答案:

答案 0 :(得分:0)

这很简单:我只需要以这种方式更改附件部分:

attachments: [
    {
        path: data
    }
]