【问题标题】:Trouble with Importing modules导入模块的问题
【发布时间】:2018-08-18 06:50:01
【问题描述】:

我的 Index.js 中有这段代码。

var express = require('express');
var router = express.Router();

var check = require('../nodemailer/check.js');
const nodemailer = require('nodemailer');

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});


router.get('/checkemail', function(req, res, next) {
var email = 'email';
console.log(email);
check.transporter.sendMail(mailOptions, function(error, info) { 
    if (error) {
        return console.log(error); 
    } 
    console.log('Message sent: %s', info.messageId);
module.exports.email= email;
//console.log(module.exports.email);
  });
 res.render('checkemail', { title: 'check' });
});
module.exports = router;

这在我的 check.js 中

var nodemailer = require('nodemailer');
var rter = require('../routes/index.js');
//var dho = rter.email;
console.log(rter.email)
var transporter = nodemailer.createTransport({ 
    host: 'server206.web-hosting.com', 
    port: 26, 
    secure: false, // true for 465, false for other ports
    auth: { 
        user: 'noreply@swiftcircle.website', // generated ethereal 
        pass:  'Miracle1994' // generated ethereal password } }); 
    }
});

var mailOptions = { 
    from: 'noreply@swiftcircle.website', 
    to: rter, // list of receivers
    subject: 'Hello', // Subject line 
    //text: 'Hello world?', // plain text body 

    html: '<b>Hello world?</b>' // html body
 };

我从索引中成功导出了变量“电子邮件”,但是当我尝试导入时它在 check.js 中显示未定义...

在代码中,我导出了变量 email,然后在 check.js 中使用 '.property' 要求它并尝试 console.log 它但它返回 'undefined' 请问我做错了什么?

【问题讨论】:

标签: node.js express node-modules


【解决方案1】:

问题出现在交织在一起的模块require 中。 index.js 模块需要第 4 行中的 check.js 模块;然后check.js 模块需要第 2 行中的index.js 模块。

这可以防止check.js 模块访问index.js 模块中的导出变量。

您可能应该考虑如何重构代码,以便可以通过其他方式访问您想要访问的 email 属性(例如,通过使用一个实用程序模块,它可以获取 email 属性在适当的时候设置和阅读)。

【讨论】:

  • 另一个问题是我必须参考 check.js 文件来获取传输器对象。我该如何解决?
  • 如果我误解了,请原谅我,但email 属性用于mailOptions 对象,它在设置email 属性之前使用。如果这是正确的,那么最简单的方法可能是创建一个外部文件email-utility.js,其具有“静态”属性email(连同一个setter 和一个getter)。然后在 index.js 和 check.js 中都需要这个实用程序文件:在 index.js 中你会调用 setter,在 check.js 中你会调用 getter(更好的是:mailOptions 应该是一个函数,这样您就可以得到email) 的当前值。我希望这可能会有所帮助!
  • 对不起,你能给我一个测试脚本的例子吗?
【解决方案2】:

我现在明白了!我就是这样做的……

exports.mail = function mail(x){
    //my codes in my check.js
}

然后,我像这样将它导入到我的 index.js 中......

var check = require('../nodemailer/check.js);
check.mail(email);

成功了!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-26
    • 2013-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多