在通过fs模块将一些数据保存到文件后,尝试通过NodeMailer发送电子邮件时遇到麻烦。
我有一个api路由,可以接受一些非常基本的JSON数据:
{
"name": "Some Name",
"email": "example@gmail.com",
"linkedIn": "https://linkedin.com/38473289472",
"comments": ""
}
当我的路线接收到该数据时,它将尝试将该数据保存到JSON文件中。通过读取当前的JSON文件来查看此人是否已经存在,如果不存在,它将写入该文件。
这很好用,但是我的问题是在此过程发生后我尝试发送电子邮件。这是完整的代码:
const fs = require('fs');
const nodemailer = require('nodemailer');
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'myemail@email.com',
pass: 'somecoolpassword',
},
});
const mailOptions = {
from: 'myemail@email.com',
to: 'myemail@email.com',
subject: 'subject',
html: `test`,
};
// This is the route
exports.register = async (req, res) => {
try {
await addApplicant(req.body);
await transporter.sendMail(mailOptions); // Does not send
res.sendStatus(200);
} catch (err) {
res.send(err);
}
};
const addApplicant = async applicant => {
return new Promise(async (resolve, reject) => {
fs.readFile('./applicants/applicants.json', 'utf8', async (err, data) => {
if (err)
reject('There was an error accessing the applicants master file.');
const allApplicants = JSON.parse(data);
if (allApplicants.hasOwnProperty(applicant.email)) {
reject('User already exists.');
}
const updatedApplicants = JSON.stringify({
...allApplicants,
[applicant.email]: { ...applicant },
});
await writeToJsonFile(updatedApplicants);
resolve();
});
});
};
const writeToJsonFile = async updatedApplicants => {
return new Promise(async (resolve, reject) => {
fs.writeFile('./applicants/applicants.json', updatedApplicants, err => {
if (err) reject('There was an error saving the applicants information');
resolve();
});
});
};
如果我在开始使用文件系统之前更改了发送电子邮件的注册路线,它将发送电子邮件并执行适当的文件操作。
exports.register = async (req, res) => {
try {
await transporter.sendMail(mailOptions); // works
await addApplicant(req.body);
res.sendStatus(200);
} catch (err) {
res.send(err);
}
};
我在这里做错了什么?老实说,它一定是一件微不足道的事情,但我现在无法看到它。