Javascript 错误:尝试使用NodeEmailer时未定义收件人,但列出了收件人

Javascript 错误:尝试使用NodeEmailer时未定义收件人,但列出了收件人,javascript,node.js,mongoose,nodemailer,Javascript,Node.js,Mongoose,Nodemailer,我一直在尝试在我的MEAN应用程序上设置和使用nodemailer。 这里是mail.js。。。我用于server.js文件的路由 'use strict'; const express = require('express'); const router = express.Router(); const nodemailer = require('nodemailer'); const config = require('./config'); const Message = require

我一直在尝试在我的MEAN应用程序上设置和使用nodemailer。 这里是mail.js。。。我用于server.js文件的路由

'use strict';
const express = require('express');
const router = express.Router();
const nodemailer = require('nodemailer');
const config = require('./config');
const Message = require('../models/message');

var transporter = nodemailer.createTransport({
  service: 'gmail',
  secure: false,
  port: 25,
  auth: {
    user: config.mailUser, //same as from in mailOptions
    pass: config.mailPass
  },
  tls: {
    rejectUnauthorized: false
  }
});

router.post('/contact', function(req, res){
  var mailOptions = new Message({
    from: 'jon.corrin@gmail.com',
    to: req.body.to,
    subject: req.body.subject,
    text: req.body.text
    //html: req.body.html
  });

  transporter.sendMail(mailOptions, function(error, info){
    if(error){
      return console.log(error);
    }
    return console.log('Message %s sent: %s', info.messageId, info.response);
  });
});

module.exports = router;
我的config.js文件如下所示

module.exports = {
  mailUser: 'jon.corrin@gmail.com',
  mailPass: 'XXXXXXXXX'
};
我使用postman对后端进行API调用,但结果是标题中指出的错误。有人知道为什么吗?看来接受者是有定义的

***更新

这是我的express应用程序

const express = require('express');
const cookieParser = require('cookie-parser');
const bodyParser = require("body-parser");
const mongoose = require('mongoose');

const appRoutes = require('./routes/app');
const keyRoutes = require('./routes/keys');
const mailRoutes = require('./routes/mail');

const app = express();
const uristring =
  process.env.MONGOLAB_URI ||
  process.env.MONGOHQ_URL ||
  'mongodb://localhost/db';


mongoose.connect(uristring, function (err, res) {
  if (err) {
    console.log ('ERROR connecting to: ' + uristring + '. ' + err);
  } else {
    console.log ('Succeeded connected to: ' + uristring);
  }
  });

app.use(express.static(__dirname + '/dist'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());

app.use(function (req,res,next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers','Origin, X-Requested-With, Content-Type, Accept');
  res.header('Access-Control-Allow-Methods', 'POST, GET, PATCH, DELETE, OPTIONS');
  next();

});

app.use('/mail', mailRoutes);
app.use('/keys', keyRoutes);
app.use('/', appRoutes);

//catch 404 and forward error handler
app.use(function (req, res, next) {
  return res.json('src/index');
});

app.listen(process.env.PORT || 8080);

module.exports = app;
这是我发出的请求

***更新

这是我的消息类

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const schema = new Schema({
  from: {type: String, required: true},
  to: {type: String, required: true},
  subject: {type: String, required: true},
  text: {type: String, required: true},
  html: {type: String, required: false}
});

module.exports = mongoose.model('Message', schema);

问题在于猫鼬模式。我不是猫鼬专家,事实上我一生中从未使用过它,但在调试您的代码时,我发现了为什么您很难弄明白这一点:

使用
console.log

let mailOptions = new Message({
        from: 'jon.corrin@gmail.com',
        to: req.body.to,
        subject: req.body.subject,
        text: req.body.text
    //html: req.body.html
 });
它的输出如下:

{ from: 'jon.corrin@gmail.com',
  to: 'some-email@gmail.com',
  subject: 'My subject',
  text: 'Email body',
  _id: 590135b96e08e624a3bd30d2 }
这似乎是一个普通的物体。事实上(不包括_id部分),其输出与以下相同:

let mailOptions = {
    from: 'jon.corrin@gmail.com',
    to: req.body.to,
    subject: req.body.subject,
    text: req.body.text
    //html: req.body.html
};
但后者在将其传递给nodemailer时起作用

{ '$__': 
   InternalCache {
     strictMode: true,
     selected: undefined,
     shardval: undefined,
     saveError: undefined,
     validationError: undefined,
     adhocPaths: undefined,
     removing: undefined,
     inserting: undefined,
     version: undefined,
     getters: {},
     _id: undefined,
     populate: undefined,
     populated: undefined,
     wasPopulated: false,
     scope: undefined,
     activePaths: StateMachine { paths: [Object], states: [Object], stateNames: [Object] },
     ownerDocument: undefined,
     fullPath: undefined,
     emitter: EventEmitter { domain: null, _events: {}, _eventsCount: 0, _maxListeners: 0 } },
  isNew: true,
  errors: undefined,
  _doc: 
   { _id: 590137d8f8c7152645180e04,
     text: 'Email body',
     subject: 'My subject',
     to: 'my-email@gmail.com',
     from: 'jon.corrin@gmail.com' } }
所以我试图找出
mailpoptions
的真实身份(就像我是JSON-Bourne或其他什么)

使用:

console.log(Object.assign({}, mailOptions));
我得到以下信息,这对NodeEmailer来说当然不好

{ '$__': 
   InternalCache {
     strictMode: true,
     selected: undefined,
     shardval: undefined,
     saveError: undefined,
     validationError: undefined,
     adhocPaths: undefined,
     removing: undefined,
     inserting: undefined,
     version: undefined,
     getters: {},
     _id: undefined,
     populate: undefined,
     populated: undefined,
     wasPopulated: false,
     scope: undefined,
     activePaths: StateMachine { paths: [Object], states: [Object], stateNames: [Object] },
     ownerDocument: undefined,
     fullPath: undefined,
     emitter: EventEmitter { domain: null, _events: {}, _eventsCount: 0, _maxListeners: 0 } },
  isNew: true,
  errors: undefined,
  _doc: 
   { _id: 590137d8f8c7152645180e04,
     text: 'Email body',
     subject: 'My subject',
     to: 'my-email@gmail.com',
     from: 'jon.corrin@gmail.com' } }
通过阅读mongoose文档,我发现了一种将其转换为简单javascript对象的方法,该对象可以很好地与NodeEmailer配合使用。该方法是:

toObject

总之,你有两个选择:

1)
transporter.sendMail(mailpoptions.toObject()/…
如果您想使用mongoose模式(我真的不知道为什么,但是…)

2)放弃mongoose模式,只需使用:(这是我推荐的方法,因为mongoose与NodeEmailer无关)


都测试过了,我发送的电子邮件没有问题。

请显示您正在执行的请求和快速设置。我编辑了包含我的快速应用程序和邮递员请求的答案检查我编辑的答案,检查您是否在邮递员请求中设置了
内容类型:application/json
。感谢您的回复。我已经将标题设置为application/json。检查我的编辑以获取postman@JonathanCorrin您是否获得了
req.body.to
的任何值?我复制了您的代码(仅express&router部分)并且工作正常。显示您的消息类,您似乎在那里遇到了问题。抱歉,延迟,我已编辑并放入我的消息类中!我去看看