TLDR is, I think I know what issue is, but do not know how to fix it:)
I have written my react app with simple contact section. See code for onSubmit:
const ContactForm: React.FC = () => {
{...}
onSubmit: async (values, { setSubmitting, resetForm }) => {
try {
const response = await fetch("https://mywebpage.com/send-contact", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(values),
});
if (!response.ok) {
throw new Error("Błąd wysyłania wiadomości");
}
setSuccessAlert(true);
resetForm();
} catch (error: any) {
alert(`Błąd: ${error.message}`);
} finally {
setSubmitting(false);
}
},
});
{...}
Secondly, I have coded nodemailer node.js backend for handling login and form of the e-mail. Credentials for nodemailer were passed through .env and it worked flawlessly in localhost. (Please note both .env and sendtoemail.js are being located in the app folder where index.html is, not in src or public)
import express, { json } from "express";
import { createTransport } from "nodemailer";
import cors from "cors";
import bodyParser from "body-parser";
import "dotenv/config";
const app = express();
const USER = process.env.EMAIL_USER;
const PASS = process.env.EMAIL_PASS;
const corsOrigin = {
origin: "https://mywebpage.com",
};
app.use(cors(corsOrigin));
app.use(json());
app.use(bodyParser.json());
app.post("/send-contact", async (req, res) => {
const { name, email, message } = req.body;
try {
let transporter = createTransport({
host: "myhost.com",
port: 465,
secure: true,
auth: {
user: USER,
pass: PASS,
},
});
let mailOptions = {
from: email,
to: USER,
subject: `Nowa wiadomość od ${name}`,
text: message,
html: `<p><strong>Nadawca:</strong> ${name} </p>
<p><strong>Email:</strong> ${email}</p>
<p><strong>Wiadomość:</strong> ${message}</p>`,
};
await transporter.sendMail(mailOptions);
transporter.verify(function (error, success) {
if (error) {
console.log(error);
} else {
console.log("Server is ready to take our messages");
}
});
res.status(200).json({ message: "Email sent successfully!" });
} catch (error) {
console.error("Error sending email:", error);
res
.status(500)
.json({ message: "Error sending email", error: error.toString() });
}
});
And when I had built my app by npm run build and upladed it on server (I have just domain with server folders such as public-html, nothing like firebase or similar) it does not log in or send my form.
I think I know why it does not work – it probably does not read or even build my node.js script + .env, but I do not not know how to safely fix it. Any help would be highly appreciated 🙂
I want to be sure that I by mistake I do not pass .env credentials to my public folder