首页 > 解决方案 > 从 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 上,我得到“未定义”。

标签: node.jsreactjsexpresspostsendgrid

解决方案


推荐阅读