如何使用NetLify功能从NodeMailer那里获得响应?

发布于 2025-01-28 02:33:11 字数 2400 浏览 5 评论 0原文

我正在使用NetLify函数来从前端发送电子邮件,并且可以正常工作...就像在此发送电子邮件一样。

但是,在客户端(浏览器)上,我无法得到任何响应。我需要一个基本响应,如果(status ===“成功”)displayMessage(),但我似乎无法在浏览器上得到任何响应,就可以使我做

我收到此消息uck offult(在承诺中)SyntaxError:JSON.PARSE:JSON DATA的第1列中的意外字符,但是在通过Postman发送请求时,我得到了“响应”的“电子邮件发送”,这是是回调响应的身体部分。

这是我在.netlify/functions/sendmail上使用的函数

const nodemailer = require("nodemailer");

exports.handler = function (event, context, callback) {
  const mailConfig = {
    host: "smtp.mailgun.org",
    port: 465,
    secure: true,
    auth: {
      user: process.env.MAILGUN_USER,
      pass: process.env.MAILGUN_PASSWORD,
    },
  };
  const transporter = nodemailer.createTransport(mailConfig);

  transporter.verify((error, success) => {
    if (error) {
      console.log(error);
    } else {
      console.log("Ready to send emails");
    }
  });

  const messageData = JSON.parse(event.body);

  const { email, name, mobile, message, subject, recipient } = messageData;

  console.log(messageData);

  const mailOptions = {
    from: email,
    to: recipient,
    subject: subject,
    text: message,
  };

  transporter.sendMail(mailOptions, (error, success) => {
    if (error) {
      console.log(error);
      callback(error);
    } else {
      console.log("email sent");
      callback(null, {
        statusCode: 200,
        body: "Email sent successfully",
      });
    }
  });
};


,在客户端,我

const form = document.querySelector("#message");

const submitMessage = (event) => {
  event.preventDefault();

  const formData = new FormData(form);

  formData.append("recipient", "[email protected]");
  formData.append("subject", "Submission from website");

  const messageData = Object.fromEntries(formData);

  console.log(messageData);

  const url = ".netlify/functions/sendMail";
  const options = {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(messageData),
  };

  fetch(url, options)
    .then((response) => response.json())
    .then((data) => console.log(data));
};

form.addEventListener("submit", submitMessage);

在fetch请求中拥有此功能,我期望data给我一个响应,以便我可以触发一些操作以显示显示成功的消息..

有人可以建议我在这里做错了什么吗?

I am using netlify functions to send an email from the frontend and it works fine... as in it does send the email.

However on the clientside (browser) I can't get any response. I need a basic response that would allow me to do a if (status==="success") displayMessage() but I can't seem to get any response on the browser.

I get this message Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data However on sending the request via POSTMAN I get a response 'Email Sent Succesfully' which is the body part of the callback response.

Here's the function that I am using at .netlify/functions/sendMail

const nodemailer = require("nodemailer");

exports.handler = function (event, context, callback) {
  const mailConfig = {
    host: "smtp.mailgun.org",
    port: 465,
    secure: true,
    auth: {
      user: process.env.MAILGUN_USER,
      pass: process.env.MAILGUN_PASSWORD,
    },
  };
  const transporter = nodemailer.createTransport(mailConfig);

  transporter.verify((error, success) => {
    if (error) {
      console.log(error);
    } else {
      console.log("Ready to send emails");
    }
  });

  const messageData = JSON.parse(event.body);

  const { email, name, mobile, message, subject, recipient } = messageData;

  console.log(messageData);

  const mailOptions = {
    from: email,
    to: recipient,
    subject: subject,
    text: message,
  };

  transporter.sendMail(mailOptions, (error, success) => {
    if (error) {
      console.log(error);
      callback(error);
    } else {
      console.log("email sent");
      callback(null, {
        statusCode: 200,
        body: "Email sent successfully",
      });
    }
  });
};


and on the client side I have this

const form = document.querySelector("#message");

const submitMessage = (event) => {
  event.preventDefault();

  const formData = new FormData(form);

  formData.append("recipient", "[email protected]");
  formData.append("subject", "Submission from website");

  const messageData = Object.fromEntries(formData);

  console.log(messageData);

  const url = ".netlify/functions/sendMail";
  const options = {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(messageData),
  };

  fetch(url, options)
    .then((response) => response.json())
    .then((data) => console.log(data));
};

form.addEventListener("submit", submitMessage);

in the fetch request, I expected data to give me a response so I could trigger some action to display a success message..

Can someone advise me what I am doing wrong here?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

罪歌 2025-02-04 02:33:11

我意识到自己在做什么错,这是其他人面临同样问题的解决方案。

在NetLify函数的回调中,我将正文发送为文本

      callback(null, {
        statusCode: 200,
        body: "Email sent successfully",
      });

,但是在clitionide提取请求中,我将其视为JSON,

  fetch(url, options)
    .then((response) => response.json())
    .then((data) => console.log(data));

因此基本上我可以使用response.text()而不是response.json()用于提取请求或使用json.stringify,然后从回调中返回JSON对象。我更喜欢json.stringify选项,如下

      callback(null, {
        statusCode: 200,
        body: JSON.stringify({
          status: "success",
          message: "Email sent successfully",
        }),
      });

I realised what I was doing wrong and here's the solution in case someone else faces the same issues.

In the callback from the netlify function I was sending the body as text

      callback(null, {
        statusCode: 200,
        body: "Email sent successfully",
      });

but in the clientside fetch request I was treating it as json

  fetch(url, options)
    .then((response) => response.json())
    .then((data) => console.log(data));

So basically I could either use a response.text() instead of response.json() for the fetch request or use JSON.stringify and return a JSON object from the callback. I preferred the JSON.stringify option as below for the callback

      callback(null, {
        statusCode: 200,
        body: JSON.stringify({
          status: "success",
          message: "Email sent successfully",
        }),
      });

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文