使用 Nodemailer 在 React 和 Express 中发出 post 请求时出现问题

Problem making a post request in React and Express with Nodemailer

我正在尝试在 express/reactjs 堆栈中使用 nodemailer,但我遇到了一些问题。

在我的 reactjs 组件中:

handleSubmit = async e => {
    console.log(e);
    e.preventDefault();
    await axios
      .post("http://localhost:5000/api/form", {
        firstName: "Name",
        lastName: "Lname"
      })
      .then(function(response) {
        console.log(response);
      })
      .catch(function(error) {
        console.log(error);
      });
  };

然后在服务器端:

app.post("api/form", (req, res) => {
  let transporter = nodemailer.createTransport({
    host: "smtp.ethereal.email",
    port: 587,
    auth: {
      user: "user",
      pass: "pass"
    }
  });

  let mailOptions = {
    from: "test@test.com",
    to: "mail@ethereal.email",
    replyTo: "test@test.com",
    subject: "New msg",
    text: "Hi",
    html: "<p>Just an email</p>"
  };

  transporter.sendMail(mailOptions, (err, info) => {
    if (err) {
      return console.log(err);
    }
    console.log("message sent: ", info.msg);
  });
});

服务器运行

const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`server in port: ${port}`));

我在控制台中遇到的错误是

POST http://localhost:5000/api/form 404 (Not Found)

和控制台错误

Error: Request failed with status code 404
    at createError (createError.js:17)
    at settle (settle.js:19)
    at XMLHttpRequest.handleLoad (xhr.js:78)

如有任何帮助,我们将不胜感激。

您收到 404 状态代码的原因是您忘记了 api/form 之前的斜线。应该是app.post('/api/form')

顺便说一下,您没有 return 回复。在您的代码正在等待的请求发出后,这将导致响应超时。

axios
  .post("http://localhost:5000/api/form", {
    firstName: "Name",
    lastName: "Lname"
  })
  .then(function(response) {
    console.log(response); // NO RESPONSE IS COMING
  })