node.js - 使用 Angular5 前端在 NodeJS 中使用 nodemailer 发送邮件
问题描述
每当我注册用户时,我想从我的 nodejs 服务器发送一封电子邮件。我使用 Angular5 作为前端。它不会返回任何错误,但它也不起作用。就像我的函数根本没有被调用。这是我尝试过的(在此示例中电子邮件不是真实的):
服务器.js
app.post('/sendMails', function(req,res) {
console.log("WENT INTO SEND MAILS!!!")
let transporter = nodemailer.createTransport({
service: 'gmail',
secure: false,
port: 25,
auth: {
user: 'someemail@gmail.com',
pass: process.env.MAIL_PASSWORD
},
tls: {
rejectUnauthorized: false
},
});
let HelperOptions = {
from: '"Babababa" <someemail@gmail.com>',
to: 'someemail@gmail.com',
subject: 'Hello world',
text: 'hey dude'
};
transporter.sendMail(HelperOptions, (error, response) => {
if(error) {
return console.log(error);
res.json({error: "API Error"});
}
else{
console.log("The message is sent: " + response.message);
res.json({response: "sent"})
}
})
});
来自角
UserService.ts(相关部分)
constructor(private http: HttpClient) { }
sendMail(user: User){
console.log("sendMail() was called.")
return this.http.post("http://localhost:3000/sendMails", user.email);
}
这在我注册时的注册组件中调用
注册.component.ts
public signUp(){
//marks all fields as touched.
this.fs.markFormGroupTouched(this.registerForm);
if(this.registerForm.valid) {
let user: User = this.registerForm.value;
console.log(user)
this.userService.createUser(user);
this.userService.sendMail(user); //<--- only this is relevant for this case.
}
else {
//shows the error messages, for the not valid input fields.
this.formErrors = this.fs.validateForm(this.registerForm,
this.formErrors, false)
}
}
当我运行此代码时,没有错误。在检查器/客户端控制台窗口中,我看到消息“sendMail() 被调用”。,这意味着它肯定在调用我的服务。但是,我没有收到任何邮件或任何错误
解决方案
内部返回一个可观察的http.post()
。sendMail()
你必须订阅这个 observable,否则它不会被执行。
所以registration.component.ts
你需要这样的东西:
this.userService.sendMail(user).subscribe(
response => {
console.log(response);
}
);
推荐阅读
- c - C 数组 memcmp 麻烦
- sublimetext3 - 如何摆脱 Sublime Text 3 上的多个窗格?
- python - Python 中的 Fibonacci o/p 不正确,因为未在同一行代码上分配值。为什么?
- node.js - 在 Log4js 中如何启用跟踪?
- angular - 我想用 Angular2 检查是否存在文件
- angular - 打开模态窗口组件
- c# - 在 MVC C# 中通过属性路由使用分页时,我们如何跳过可选的空参数?
- c# - AWS Cogntio:注册/登录后如何在 .Net 中发出身份验证请求
- c++ - Qt QByteArray 无符号数据类型
- ios - 带有图像和文本的自定义按钮