[英]Unable to import another .js file
//email.js
module.exports = function send() {
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'test@gmail.com',
pass: 'password'
}
});
var mailOptions = {
from: 'test@gmail.com',
to: 'test@gmail.com',
subject: 'Revenue Report',
text: "Hello"
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent Successfully' + info.response);
}
});
};
var mail = require('./email.js')();
mail.send();
我正在尝试从 email.js 导入 function。
但是,我收到了这个错误:TypeError: Cannot read properties of undefined (reading 'send')。
我的代码有什么问题? 有什么解决办法吗?
您正在直接导出function
,因此它不会与您应该使用的任何 object 包装在一起.send()
。
你可以简单地做,
// just import
var mail = require('./email.js');
// then call it
mail();
或者
// call as soon as imported
require('./email.js')();
如果您想将send()
方法保留在object
中,您应该像这样导出它,
function send() {
// Your code
}
module.export = {
send
}
然后你可以像这样导入和使用它
var mail = require('./email.js');
mail.send();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.