I have built a static website in React with a simple contact form on the contact page.
For the form submissions I have used Nodemailer. On my localhost I can run node and run my 'server.js' file that handles the submission. 100% working on my localhost, no issues.
I have since deployed my React website on cPanel hosting (Namecheap), website all working well. Now comes the issue, trying to set up Node with my server.js file on cPanel, to fire when I submit the contact form.
Namecheap has the option to set up a Node application, which I have done using a subdomain (node.smdev.au) as far I can tell it is loading my file correctly.
My problem now is getting my contact form to submit just like it did on my localhost environment.
Here are a few more details:
The Node app is set up on a root level subdomain at node.smdev.au/form
My React website is at public_html/smdev.au or https://smdev.au (form is on https://smdev.au/contact)
Code of my ContactForm component:
import React, { useState } from "react"
const ContactForm = () => {
const [status, setStatus] = useState("Submit");
const [formSuccess, setFormSuccess] = useState("");
const [formError, setFormError] = useState("");
const handleSubmit = async (e) => {
const { name, email, phone, service, message } = e.target.elements;
let details = {
name: name.value,
email: email.value,
message: message.value,
service: service.value,
phone: phone.value
}
e.preventDefault();
if(name.value == '' || email.value == '' || phone.value == '' || message.value == '' ){
setFormError('Please fill in all required fields.');
setFormSuccess('');
}else{
setFormError('');
setStatus("Sending...");
let response = await fetch("https://smdev.au/contact", {
method: "POST",
headers: {
"Content-Type": "application/json;charset=utf-8",
},
body: JSON.stringify(details),
});
setStatus("Submit");
let result = await response.text();
console.log(result)
e.target.reset();
setFormSuccess('Thankyou, your enquiry has been sent.');
}
}
return(
<form onSubmit={handleSubmit} id="contactForm">
<div className="row">
<div className="form-group col-md-12 mb-3">
<label htmlFor="name">Your Name *</label>
<input
type="text"
name="name"
className="form-control"
required/>
</div>
<div className="form-group col-md-12 mb-3">
<label htmlFor="email">Email Address *</label>
<input
type="email"
name="email"
className="form-control"
required/>
</div>
<div className="form-group col-md-12 mb-3">
<label htmlFor="phone">Phone Number *</label>
<input
type="text"
name="phone"
className="form-control"
required/>
</div>
<div className="form-group col-md-12 mb-3">
<label htmlFor="service">Which service are you interested in?</label>
<select
type="select"
name="service"
className="form-control"
id="service"
required>
<option value="">Choose...</option>
<option value="Website Design and Development">Website Design and Development</option>
<option value="Online Store Development">Online Store Development</option>
<option value="Website Updates">Website Updates</option>
<option value="Email Collateral">Email Collateral</option>
</select>
</div>
<div className="form-group col-md-12 mb-3">
<label htmlFor="message">Comments/Details *</label>
<textarea
name="message"
className="form-control"
rows="2"
required/>
</div>
<div className="form-group col-md-12 mb-3">
<button className="btn btn-primary">{status}</button>
</div>
{formError && <p className="error">{formError}</p>}
{formSuccess && <p className="success">{formSuccess}</p>}
</div>
</form>
)
}
export default ContactForm;
Code of the server.js file:
const express = require('express');
const cors = require('cors');
const nodemailer = require('nodemailer');
const dotenv = require('dotenv');
const router = express.Router();
const app = express();
const PORT = process.env.PORT || 5000; //not sure if this is actually doing anything
app.use(cors());
app.use(express.json());
app.use("https://smdev.au/", router);
// app.listen(PORT, ()=>{
// console.log(`Server running on port ${PORT}`);
// });
// app.get('/', (req, res) => {
// res.send('https://smdev.au/contact');
// });
require('dotenv').config();
const contactEmail = nodemailer.createTransport({
host: "myweb.web-hosting.com",
port: 465,
secure: true,
auth: {
user: `${process.env.REACT_APP_MYUSER}`,
pass: `${process.env.REACT_APP_MYPW}`,
},
debug: true, // show debug output
logger: true // log information in console
});
contactEmail.verify((error) => {
if (error) {
console.log(error);
} else {
console.log("Ready to Send");
}
});
router.post("https://smdev.au/contact", (req, res) => {
const name = req.body.name;
const email = req.body.email;
const phone = req.body.phone;
const service = req.body.service;
const message = req.body.message;
const mail = {
from: 'info@smdev.au',
to: "info@smdev.au",
subject: "Contact Form Submission",
html: `<p>Name: ${name}</p>
<p>Email: ${email}</p>
<p>Phone: ${phone}</p>
<p>Service: ${service}</p>
<p>Message: ${message}</p>`,
};
contactEmail.sendMail(mail, (error) => {
if (error) {
res.json({ status: "ERROR" });
} else {
res.json({ status: "Message Sent" });
}
});
});
//a check to see node is running
var http = require('http');
var server = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
var message = 'It works!\n',
version = 'NodeJS ' + process.versions.node + '\n',
response = [message, version].join('\n');
res.end(response);
});
server.listen();
Once again totally works on local environment where I have Node installed. Just got no idea how to implement it on cPanel. I feel it has something to do with the URLs and ports etc. but got no idea.