node.js - 从 Express POST 请求中获取数据
问题描述
我正在尝试 console.log 我通过 POST 请求发送到我的服务器的数据。这是代码:
前端:
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 形式放在 fetch 请求上,它是我的服务器可以识别的形式。但我对此的逻辑可能是错误的。在服务器端代码的 console.log 上,我得到“未定义”。
解决方案
推荐阅读
- reactjs - ApolloGraphQL 和 React:组件重新挂载时避免调用查询和订阅?
- javascript - 不考虑用户时区
- scheme - 方案/球拍中最大的整数值是多少?
- python - 如何使用插入排序对单链表进行排序?
- c - 尝试从 C 编程语言完成 E1-19 时出现分段错误错误
- express - 如何修复来自 url 的空查询字符串
- excel - 如何将 Excel 工作表上的图片名称转换为 VBA 变量
- dart - 如何为整个 MaterialApp 的主题设置背景颜色?
- java - 在浏览器中附加 /cmis/json 后部署的应用程序 URL 不起作用
- linux - 为什么我们不能使用 esp 寄存器直接引用内存地址?