Контактная форма с nodemailer

Я использую 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: "[email protected]",
       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 <[email protected]>", 
   to: "Receiver Name <[email protected]>", 
   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)
           );
    });

    };

    }
  ]);

person Ankit    schedule 10.03.2016    source источник
comment
Как вы отправляете динамические данные, какую кодировку используете?   -  person Royal Pinto    schedule 10.03.2016


Ответы (1)


Ааа, думаю, нашел. Вы повторно инициализируете app как var app = express(); в строке 24. Следовательно, какие бы синтаксические анализаторы вы ни установили, на самом деле они не используются. Просто удалите это, и вы сможете получить данные.

person Royal Pinto    schedule 10.03.2016
comment
о, я понял, это была моя вина, извини ... ты был прав. Спасибо за ваше время :) - person Ankit; 10.03.2016