首页 > 解决方案 > 导入模块的问题

问题描述

我的 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.jsexpressnode-modules

解决方案


问题出现在require模块的交织中。该index.js模块需要第check.js4 行中的模块;然后该check.js模块需要第index.js2 行中的模块。

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

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


推荐阅读