I have a contact form on my website that I created with Node.js. When I run the site as a local host (localhost:5000), everything works fine. I fill out the contact form and when I hit send, I get a thank you alert and the email goes through.
However, once I connected my site to a domain and had it live, it no longer works - I get the "invalid login" message. I wrote an "if statement" in JS to return this "invalid login" error if the request does not go through, which is what I keep getting.
Could it be that I am not connecting to the correct server?
I'm guessing the xhr variable I use in my code is not valid once I begin using an actual hosting service. If so, how can I fix that?
Here is my code.
form.addEventListener('submit', (e)=>{
e.preventDefault();
console.log('submit clicked')
let formData = {
email: email.value,
level: password.value,
amount: amount.value,
service: service.value,
details: details.value,
email: email.value
}
let xhr = new XMLHttpRequest();
xhr.open('POST', '/');
xhr.setRequestHeader('content-type', 'application/json');
xhr.onload = function() {
console.log(xhr.responseText);
if (xhr.responseText == 'success'){
alert('Thank you! An Ogma representative will contact you shortly.');
email.value = '';
password.value = '';
amount.value = '';
service.value = '';
details.value = '';
email.value = '';
}else{
alert('Invalid login')
}
}
xhr.send(JSON.stringify(formData));
})
Edit: Here is my code with nodemailer. It is my Server.js file.
const express = require('express');
const app = express();
const nodemailer = require("nodemailer");
const PORT = process.env.PORT || 5000;
//Middleware
app.use(express.static('public'));
app.use(express.json())
app.get('/', (req, res)=>{
res.sendFile(__dirname + '/public/Request.html')
})
app.post('/', (req, res)=>{
console.log(req.body);
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: '//kept hidden',
pass: //kept hidden
}
})
const mailOptions = {
from: req.body.email,
to: '//kept hidden',
subject: 'New message from Ogma',
text: [req.body.email, req.body.password, req.body.amount, `req.body.service, req.body.details].join('\n\n')`
}
transporter.sendMail(mailOptions, (error, info) =>{
if(error){
console.log(error);
res.send('error');
} else {
console.log('Email sent: ' + info.response);
res.send('success')
}
})
})
app.listen(PORT, ()=>{
console.log('Server running on port ${PORT}')
})