Node.js 如何将express Nodejs中的post请求对象导出到另一个模块
这段代码返回的数据对象包含用户的表单输入,与我预期的完全一致。我使用了一个变量contactFormInfo来包含该对象,当我使用console.log(contactFormInfo)时,我会在代码底部对该对象进行注释。我的问题是如何将此对象导出到另一个模块mailer.js中,在该模块中我要提取用于发送电子邮件的信息。作为一个新手,我被困住了,任何帮助都是非常感谢的Node.js 如何将express Nodejs中的post请求对象导出到另一个模块,node.js,express,Node.js,Express,这段代码返回的数据对象包含用户的表单输入,与我预期的完全一致。我使用了一个变量contactFormInfo来包含该对象,当我使用console.log(contactFormInfo)时,我会在代码底部对该对象进行注释。我的问题是如何将此对象导出到另一个模块mailer.js中,在该模块中我要提取用于发送电子邮件的信息。作为一个新手,我被困住了,任何帮助都是非常感谢的 const express = require('express'); const app = express(); //
const express = require('express');
const app = express();
// register view engine
app.set('view engine', 'ejs');
//Http listening app
app.listen(5000, ()=> console.log('Server is listenong on port 5000'));
//Middleware and static files
app.use(express.static('public'));
//Render Home Page
app.get('/', (req, res) => { res.render('index')});
app.use(express.urlencoded({ extended: true }));
//Receiving submit-form data through post request
app.post('/', (req, res)=> { let contactFormInfo = req.body;
res.redirect('/');
res.end();
console.log(contactFormInfo);
});
//OUTPUT WHEN I console.log(contactFormInfo);
/*
{
name: 'John Doe',
email: 'jdoe@outlook.com',
subject: 'Brand development',
mobile: '0722200000',
message: 'Please call or email'
};
*/
您需要创建一个函数,该函数的逻辑是根据收到的参数发送电子邮件,并在存在路由逻辑的地方导入此函数
并使用contactFormInfo变量从route调用mailer.js中的函数。您可以使用以下方法:-
import sgMail from '@sendgrid/mail'
sgMail.setApiKey(process.env.SENDGRID_API_KEY)
const sendWelcomeEmail = (userEmail, nameOfUser) => {
sgMail.send({
to: userEmail,
from: 'example@gmail.com',
subject: 'Welcome to Task Manager Application',
text: `Hi There!!! How are you ${nameOfUser}?.`
//html: '<strong>and easy to do anywhere, even with Node.js</strong>',
});
}
export {
sendWelcomeEmail,
};
非常感谢您的回复。至少现在我有了另一种方法,我一直认为有一种方法可以导出object非常感谢Jatin,因为我已经有了一个工作的NodeEmailer模块,我将把它包装在一个函数中并导入app.js
app.post('/', (req, res)=> { let contactFormInfo = req.body;
res.redirect('/');
res.end();
sendWelcomeEmail(contactFormInfo.name,contactFormInfo.email) //pass any properties you want to use in your mail.
console.log(contactFormInfo);
});