我使用nodemailer发送邮件,邮件包含提交时表单中的所有信息。我发送静态数据时,我已成功发送邮件。但是在从表单传递动态数据时,我得到了未定义的错误。
Cannot read property 'name' of undefined
app.js
var express = require('express');
var nodemailer = require("nodemailer");
var bodyParser = require('body-parser');
var smtpTransport = nodemailer.createTransport("SMTP",{
service: "Gmail", // sets automatically host, port and connection security settings
auth: {
user: "myemail@gmail.com",
pass: "mypass"
}
});
http = require("http"),
fs = require('fs'),
cors = require('cors');
process.on('uncaughtException', function(err) {
console.log('Caught exception: ' + err);
});
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
// cross origin:
app.all('*', function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
// end of cross
var config = require("./app/config.js")();
//Folder config.
app.use(express.static(__dirname + '/app/public/'));
app.use(express.static(__dirname + '/app/public/app/'));
app.get('/', function(req, res) {
res.sendfile('index.html');
});
app.post('/contact', function(req, res) {
console.log(req.body);
var data= req.body;
smtpTransport.sendMail({
from: "Sender Name <sender@gmail.com>",
to: "Receiver Name <reciver@gmail.com>",
subject: "Confirmation Mail",
text: "Messege From "+data.name
}, function(error, response){ //callback
if(error){
console.log(error);
}else{
console.log(" Message sent");
}
smtpTransport.close(); // shut down the connection pool, no more messages. Comment this line out to continue sending emails.
});
res.json(data);
});
http.createServer(app).listen(config.port, function() {
console.log("server listening on port " + config.port + " in " + config.mode + " mode");
console.log("http://localhost:" + config.port);
});
contact.js
'use strict';
angular.module('myApp')
.controller('ContactCtrl',['$scope', '$http', '$mdToast', '$animate',
function($scope, $http, $mdToast, $animate){
$scope.toastPosition = {
bottom: true,
top: false,
left: false,
right: true
};
$scope.getToastPosition = function() {
return Object.keys($scope.toastPosition)
.filter(function(pos) { return $scope.toastPosition[pos]; })
.join(' ');
};
this.sendMail = function() {
var data = ({
name :this.name,
email :this.email,
message :this.message
})
//Post Request
$http.post('/contact', data).
success(function(response, status, headers, config){
$mdToast.show(
$mdToast.simple()
.textContent('Thanks for your message '+data.name)
.position($scope.getToastPosition())
.hideDelay(50000)
);
}).
error(function(response, status, headers, config) {
$mdToast.show(
$mdToast.simple()
.textContent('Something went wrong, Please TRY AGAIN '+data.name)
.position($scope.getToastPosition())
.hideDelay(5000)
);
});
};
}
]);
答案 0 :(得分:1)
啊,我想我找到了。您在第24行重新初始化 app
为var app = express();
。因此,您设置的任何解析器实际上都没有被使用。只需删除它,您就应该能够获取数据。