我试图尝试通过POST请求发送到服务器的console.log数据。这是代码:
前端:
onFormSubmit = (e) => {
e.preventDefault();
if (!this.state.name || !this.state.email || !this.state.message) {
this.setState(() => ({ error: 'Please fill out all the above fields!' }));
} else {
this.setState(() => ({ error: '' }));
fetch('/contact', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: this.state.name,
email: this.state.email,
message: this.state.message
})
})
.then((res) => res.json())
.then((response) => console.log('Success:', JSON.stringify(response)))
.catch((error) => console.error('Error:', error));
}
}
后端
app.post('/contact', (req, res) => {
console.log(req.body);
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
to: 'email',
from: 'email',
subject: 'New Message From Portfolio',
text: 'test',
html: '<strong>and easy to do anywhere, even with
Node.js</strong>',
};
sgMail.send(msg)
.then(() => {
console.log("email send successful");
})
})
我正在使用sendGrid发送电子邮件。我收到电子邮件时,sendGrid代码成功。我认为,通过将它以JSON形式放在获取请求上,就可以使它成为服务器可以识别的形式。但是我对此的逻辑可能是错误的。在服务器端代码的console.log上,我得到“未定义”。