尝试从React向Express发送数据时无法读取属性

时间:2018-12-05 11:26:48

标签: javascript reactjs express mailgun

我正在尝试将一些数据从React表单发送到我的Express后端。为此,我使用fetch来尝试从react发送一些可变数据。我正在控制台中记录数据,然后再运行获取以查看数据是否存在,控制台日志可以查看数据。 我的错误状态

[0] (node:2966) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'message' of undefined

所以看来我的Express后端看不到变量数据。

我如何从react发送数据

handleSubmit = async e => {
    e.preventDefault();
    console.log("Submit was pressed!");
    if (this.state.email === "") {
    }
    const { name } = this.state;
    const query = this.state.query;
    const subject = "kontakt fra nettside";
    const message = { name, query };
    console.log(message.name, message.text, "data is");
    fetch(
      "http://localhost:5000/api/email", variabler
      {
        method: "POST",
        cache: "no-cache",
        headers: {
          "Access-Control-Allow-Origin": "*",
          "Access-Control-Allow-Credentials": true,
          content_type: "application/json"
        },
        body: JSON.stringify(message, subject)
      }
    ); //.then(response => response.json());
  };

我的文件,用于从Express中的前端检索数据

 const emailConfig = require("./emailConfig")();
    const mailgun = require("mailgun-js")(emailConfig);
    exports.sendEmail = (recipient, message, attachment) =>
      new Promise((resolve, reject) => {
        const data = {
          from: "Test <test@test.no>", // Real email removed from this post
          to: recipient,
          subject: message.subject,
          text: message.query,
          inline: attachment,
          html: message.html
        };

        mailgun.messages().send(data, error => {
          if (error) {
            return reject(error);
          }
          return resolve();
        });
      });

和sendMail.js

const express = require("express");
const sendMail = express.Router();
const emailUtil = require("./emailUtil");
const { sendEmail } = emailUtil;
sendMail.post("/", async (req, res, next) => {
  // const { recipient, message } = req.body;
  console.log("Request mottatt");
  const recipient = "test@test.no";
  const message = req.body.message;
  try {
    await sendEmail(recipient, message);
    res.json({ message: "Your query has been sent" });
    console.log("Message has been sent");
    await next();
  } catch (e) {
    await next(e);
    console.log("nah", e);
  }
});
module.exports = sendMail;

我不知道错误在哪里,有什么主意吗? :)

0 个答案:

没有答案