我2個明示中間件之間傳遞數據如被設定在函數(中間件1)我的變量之一未定義,並且需要在中間件2其功能範圍(外部訪問)。當我在我的第二個中間件中使用console.log req.invoice時,它記錄正確,所以我知道我已經正確地傳遞了中間件之間的數據,但是當試圖使用我的變量在我的第二個中間件中構建一個新對象時,req.invoice是未定義。傳數據內對象
var express = require('express');
var app = express();
var Invoice = require('../models/Invoice');
var router = express.Router();
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var expressValidator = require('express-validator');
var fs = require('fs');
//Used to create a pdf invoice
var PDFDocument = require('pdfkit');
//Route
router.route('/:item')
.post(generateInvoice, sendMail, function(req, res){
});
//First middleware
var fileName, dest, invoiceNr;
function generateInvoice (req, res, next) {
//Destination for storing the invoice file
dest = __dirname + '/../static/';
//generate invoice nr
Invoice.find(function(err, invoices){
if(err) {
return res.send(err);
} else {
invoiceNr = invoices.length + 1;
fileName = 'invoice' + invoiceNr + '.pdf';
req.invoicePath = path.resolve(dest + fileName);
generate();
}
});
//Create the invoice and store in static directory
function write() {
doc = new PDFDocument();
doc.pipe(fs.createWriteStream(dest + fileName));
doc.text(invoice, 100, 100);
console.log('File written > ' + fileName + '\n Destination: ' + dest);
doc.end();
}
function generate (err){
if (err)
throw err;
if (invoiceNr !== undefined) {
write();
}
}
next();
}
//Second middleware
//I'm using mailgun-js to send the invoice via email
function sendMail(req, res, next){
//Mailgun implementation
var api_key = 'MY_KEY';
var domain = 'MY_DOMAIN';
var mailgun = require('mailgun-js')({apiKey: api_key, domain: domain});
var data = {
from: 'APP_MAIL',
to: '[email protected]',
subject: 'Hello',
text: 'Should include attachment!',
//req.invoicePath is undefined when it should be a filepath
attachment: req.invoicePath
//when invoicePath was set as a static string, the attachment was included in the email
//attachment: '/Users/anton/Desktop/app/src/server/static/invoice27.pdf'
};
//again I'm using mailgun-js for sending the emails
mailgun.messages().send(data, function (error, body) {
console.log('Message body: ' + body);
//This works and I get the above: '/Users/anton/Desktop...' in the console
console.log('The path to the invoice: ' + req.invoicePath);
//Works properly as well
console.log('The path is of type: ' + typeof(req.invoicePath));
});
res.end();
}
我設置req.invoicePath像這是我的第一個中間件。
req.invoicePath = path.resolve(dest + fileName);
如何用發送電子郵件mailgun簡要說明可以在mailgun blog here 發現在所有的任何幫助非常感謝,謝謝!
哪裏是第一中間件和第二中間件?你的'sendMail()'函數沒有輸出,也沒有修改任何東西,所以我們不確定它應該做什麼?請顯示第一個中間件和第二個中間件的實際代碼。 – jfriend00
好的,我會確保編輯我的問題,以便更容易地遵循。 –