将路由处理程序委托给NodeJS+Express中的其他模块
Delegate route handlers to other modules in NodeJS+Express
我一直在努力避免routes.js文件中的开销。
给你:
module.exports = function(app, db) {
app.get('/', function(req, res) {
res.render('index')
});
app.get('/contact-us', function(req, res) {
var col = db.collection('contacts');
var transporter = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: 'gmail.user@gmail.com',
pass: 'userpass'
}
});
});
});
}
正如您所看到的,仅仅通过实例化mongo集合和邮件传输程序,这已经被业务逻辑淹没了。我找不到任何关于如何将此逻辑委托给外部模块的材料,例如sendmail.js、savetomongo.js等
有什么建议吗?
我做了一些修改。我已经根据您的要求进行了更新。你需要根据自己的实际需要来做。
var sendmail = require('./sendmail.js');
var savetomongo = require('./savetomongo.js');
module.exports = function(app, db) {
app.get('/', function(req, res) {
res.render('index')
});
app.get('/contact-us', function(req, res) {
var col = db.collection('contacts');
var document = {'id': 'xyz'};
savetomongo.save(col, document, function(error, is_save) {
if (error) {
//handle error
} else {
// next()
sendmail.sendEmail('DUMMY <from@xyz.com>', 'to@xyz.com', 'TestEmail', 'Only for testing purpose', function(error, isSend) {
if (error) {
//handle error
} else {
// next()
//res.render('index')
}
});
}
});
});
}
//sendmail.js
module.exports = {
sendEmail: function(fromEmailFormatted, toEmail, subject, message, fn) {
var mailOptions = {
from: fromEmailFormatted, // sender address
to: toEmail, // list of receivers
subject: subject, // Subject line
html: message // html body
};
var transporter = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: 'gmail.user@gmail.com',
pass: 'userpass'
}
});
// send mail with defined transport object
transporter.sendMail(mailOptions, function(error, info) {
if (error) {
return fn(error);
} else {
return fn(null, true);
}
});
}
}
//savetomongo.js
module.exports = {
save: function(col, data, fn) {
col.insert(data, {w: 1}, function(err, records) {
if (err) {
return fn(err);
} else {
return fn(null, records);
}
});
}
}
相关文章:
- nodejs/express包含本地js文件
- 将路由处理程序委托给NodeJS+Express中的其他模块
- NodeJS Express中的分页方法
- AngularJS路由服务器端支持(NodeJS+express)
- 简单的单元测试 nodeJS/Express
- NodeJS + Express 404 在基本路由上
- nodejs/express获取发布的数据
- Nodejs Express 4 Routing Questin
- 使用nodejs/express时出现意外的换行符
- 如何使用 NodeJS Express 服务器在 HTML 中包含 JS 文件
- 在nodejs (express/http)中获取url的响应
- NodeJS express - 无法获取路由
- Nodejs - Express JSON 解析器无法响应
- 如何通过Postman将JSON发送到NodeJS Express Server
- 如何将 EmberJS 前端与 NodeJS Express API 连接
- NginX 代理 Nodejs/Express - 静态文件上的 404
- 在 nodejs Express app 中的链接中发送 DELETE 请求
- Nodejs Express - methodOverride 不适用于多部分/表单数据
- nodejs express mongoose connect to db error
- NodeJS Express 中的异步操作