0

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", "testing@gmail.com");
  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?

Alim Bolar
  • 479
  • 4
  • 17

1 Answers1

0

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",
        }),
      });

Alim Bolar
  • 479
  • 4
  • 17