POST https://toddstuke-dev.herokuapp.com/contact 404 (Not Found) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON

Viewed 54

I am trying to connect the contact page of my react portfolio to nodemailer npm in the server.js to send me emails when someone fills out the form. It worked fine when running locally and hardcoding "http://localhost:5000/contact" as the fetch url. But when I deployed to heroku and changed the fetch url to "process.env.API_URL" it throws the error in the title. I know this is probably an easy fix that I'm just missing but I have exhausted google and searched stack overflow already. Any help is appreciated.

fetch code:

const handleSubmit = async (e) => {
    const url = `${process.env.API_URL}/contact`;
    e.preventDefault();
    // console.log(formState);
    try {
      let response = await fetch(url, {
        method: "POST",
        headers: {
          "Content-Type": "application/json;charset=utf-8",
        },
        body: JSON.stringify(formState),
      });
      let result = await response.json();
      alert(result.status);
    } catch (err) {
      console.log(err);
    }
    setFormState({
      name: "",
      email: "",
      message: "",
    });
    e.target.reset();
    console.log(formState);
};

server.js here:

const express = require("express");
const router = express.Router();
const cors = require("cors");
const nodemailer = require("nodemailer");
const PORT = process.env.PORT || 5000;
const dotenv = require("dotenv");
const path = require("path");

dotenv.config();

const app = express();
if (process.env.NODE_ENV === "production") {
  const root = require("path").join(__dirname, "build");
  app.use(express.static(root));
  app.get("*", (req, res) => {
    res.sendFile("index.html", { root });
  });
}

// if (process.env.NODE_ENV === "production") {
//   app.use(express.static(path.join(__dirname, "../../client/dist")));
// }
// app.get("*", (req, res) => {
//   res.sendFile(path.join(__dirname, "../../client/dist/index.html"));
// });

app.use(cors());
app.use(express.json());
app.use("/", router);
app.listen(PORT, () => console.log("Server Running"));
console.log(PORT);
var smtpTransport = require("nodemailer-smtp-transport");

var contactEmail = nodemailer.createTransport(
  smtpTransport({
    service: "gmail",
    auth: {
      user: "tddstuke@gmail.com",
      pass: process.env.PASSWORD,
    },
  })
);

contactEmail.verify((error) => {
  if (error) {
    console.log(error);
  } else {
    console.log("Ready to Send");
  }
});

router.post("/contact", (req, res) => {
  const name = req.body.name;
  const email = req.body.email;
  const message = req.body.message;
  const mail = {
    from: name,
    to: "tddstuke@gmail.com",
    subject: "Contact Form Submission",
    html: `<p>Name: ${name}</p>
             <p>Email: ${email}</p>
             <p>Message: ${message}</p>`,
  };
  contactEmail.sendMail(mail, (error) => {
    if (error) {
      res.json({ status: "ERROR" });
    } else {
      res.json({ status: "Message Sent" });
    }
  });
});

UPDATE I was unable to find a solution to the nodemailer/fetch issue so I ended up going a different direction and using Emailjs instead. It works like a charm and was super easy to code. This is the tutorial I used in case any one else runs into this issue and wants to try a different approach as well. https://www.youtube.com/watch?v=I4DKr1JLC50

0 Answers
Related