【发布时间】:2018-09-09 23:43:11
【问题描述】:
我对 Web 开发非常陌生。我正在尝试制作一个与我们联系的表单,当用户单击提交时,表单的内容应发送到电子邮件。 我关注了这个 youtube 视频:https://www.youtube.com/watch?v=EPnBO8HgyRU
当我尝试通过 Postman 发布到我的后端 url (http://localhost:3001/api/contactus) 时,它确实会发送一封电子邮件,但所有 'req.body' 都在电子邮件中返回未定义。当我从前端联系我们表单发帖时,我在控制台中收到此错误:console error
我不明白我做错了什么。正如我所说,我是 Web 开发的新手。我正在学习,所以我不知道我不知道什么,因此我相信这可能是一个非常简单的解决方法,但它超出了我的范围。
这是我认为当我引入“axios”时出现问题的表单的前端代码。
async handleSubmit(e) {
e.preventDefault();
const err = this.validateForm();
if (err) {
if (this.state.userName.length < 2) {
this.setState({
userNameError: true,
});
}
if (this.state.email.indexOf("@") === -1) {
this.setState({
emailError: true,
});
}
if (this.state.subject.length < 2) {
this.setState({
subjectError: true,
});
}
if (this.state.message.length < 2) {
this.setState({
messageError: true,
});
}
}
if (!err) {
const finalForm = {
userName: this.state.userName,
email: this.state.email,
subject: this.state.subject,
message: this.state.message,
};
if (this.state.imagePreviewUrl) {
let newFileName = this.state.fileName.replace(/^C:\\fakepath\\/, "");
finalForm.attachments = [{
filename: newFileName,
content: this.state.imagePreviewUrl.split("base64,")[1],
encoding: 'base64',
}]
}
const contactus = await axios.post('/api/contactus', {finalForm})
this.handleFormClear(e);
this.setState({
formSubmit: true,
});
}
}
我还希望 const contactus 为“req.body”采用“finalForm”,但由于某种原因不起作用。帮助:(
这是我的后端代码:
const express = require('express')
const bodyParser = require('body-parser')
const nodemailer = require('nodemailer')
const Form = express()
Form.use(bodyParser.json())
Form.use(bodyParser.urlencoded({ extended: false}))
Form.post('/api/contactus', (req, res) => {
console.log(req.body);
const htmlEmail = `
<h3>Contact Details</h3>
<ul>
<li>Name:${req.body.userName}</li>
<li>Email:${req.body.email}</li>
<li>Subject${req.body.subject}</li>
</ul>
<h3>Messages</h3>
<p>${req.body.message}</p>
`
const transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
user: 'xxxxxxxx@gmail.com',
pass: 'xxxxxxxx',
}
});
const mailOptions = {
from: req.body.userEmail,
to: 'xxxxxxx@gmail.com',
subject: req.body.subject,
text: req.body.userMessage + '\n\n' + "Send your response to: " + req.body.userEmail,
html: htmlEmail,
attachments: req.body.attachments && req.body.attachments
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.log(error.message)
} else {
console.log('Message Sent: %s' , info.message)
console.log('Message URL: %s', nodemailer.getTestMessageUrl(info))
}
});
})
const PORT = process.env.PORT || 3001
Form.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`)
})
请帮忙。谢谢!
新的错误图片:updated error
【问题讨论】:
-
根据 SO 指南,所有错误消息都必须以文本形式输入,而不是以图像形式发布。这允许人们将消息复制粘贴到搜索引擎中,并且更容易阅读。图像中的文本可能难以阅读,尤其是在移动设备上。此外,图像使用更多日期,这对许多人来说可能是移动设备上的一个问题。你可以
edit你发帖修复。更多信息请访问help section
标签: node.js reactjs http-status-code-404 sendmail nodemailer