Why my contact form is working on localhost but not working when uploaded to web host?

Viewed 390

My contact form is working absolutely fine on localhost, but when I am uploading the code to the web(I am using Bluehost as my host) my code is not working. This is a part of my code in server.js:

const { text } = require('express');
const express = require('express');
const app = express();

require('dotenv').config(); //{path: 'custom/path/.env'}
const nodemailer = require("nodemailer");
const PORT = process.env.PORT || 9000;

//Middleware 
app.use(express.static('public_html'));
app.use(express.json())

app.get('/', (req, res)=>{
    res.sendFile(__dirname + '/public_html/ContactUs.html')
    res.sendFile(__dirname + '/public_html/index.html')
})

app.post('/', (req, res)=> {
    console.log(req.body)

    const transporter = nodemailer.createTransport({
        service: 'gmail',
        auth: {
            user: 'abc@yahoo.com',
            pass: '1234'
        }
    })
    
    const mailOptions = {
        from: req.body.email,
        to: 'abc@yahoo.com',
        subject: `Message from: ${req.body.firstname} ${req.body.lastname}`,
        text: `Name: ${req.body.firstname} ${req.body.lastname}\nEmail: ${req.body.email}\nPhone: ${req.body.phone}\n\nMessage: ${req.body.message}`
    }

    transporter.sendMail(mailOptions, (error, info) =>{
        if(error){
            console.log("error")
            res.send('error')
        } else {
            if (req.body.email === "" || req.body.firstname === "" || req.body.message === "") {
                console.log("Email, name, and message field is required!")
                res.send('Email, name, and message field is required!')
            } else if (validateEmail(req.body.email) == false){
                console.log("Enter a valid email")
                res.send('Enter a valid email')
            } else {
                console.log('Email sent:' + info.response)
                res.send('success')
            }
        }
    })
})

app.listen(PORT, ()=>{
    console.log(`Server running on port ${PORT}`)
})

function validateEmail(email) {
    var re = /\S+@\S+\.\S+/;
    return re.test(email);
}

here is my ContactUs.html code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.3/dist/umd/popper.min.js" integrity="sha384-eMNCOe7tC1doHpGoWe/6oMVemdAVTMs2xqW4mwXrXsW0L84Iytr2wi5v2QjrP/xp" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/js/bootstrap.min.js" integrity="sha384-cn7l7gDp0eyniUwwAZgrzD06kc/tftFf19TOAs2zVinnD/C7E91j9yyk5//jjpt/" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="css/contact.css">
    <link href="https://fonts.googleapis.com/css2?family=Source+Sans+Pro:wght@300&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"/>
</head>
<body>
    <!-- contact form -->
    <div class="contact-section">
        <div class="contact-wrapper">
            <div class="contact-title">Send us a Message</div>
            <form class="contact-form">
                <div class="dbl-inputs">
                  <div class="field">
                    <input type="text" id="firstname" name="firstname" placeholder="Enter your first name">
                    <i class='fas fa-user'></i>
                  </div>
                  <div class="field">
                    <input type="text" id="lastname" name="lastname" placeholder="Enter your last name">
                    <i class='fas fa-user'></i>
                  </div>
                </div>

                <div class="dbl-inputs">
                  <div class="field">
                    <input type="text" id="phone" name="phone" placeholder="Enter your phone">
                    <i class='fas fa-phone-alt'></i>
                  </div>
                  <div class="field">
                    <input type="text" id="email" name="email" placeholder="Enter your email">
                    <i class='fas fa-envelope'></i>
                  </div>
                </div>

                <div class="message">
                  <textarea placeholder="Write your message" name="message" id="message"></textarea>
                  <i class="fas fa-comment-alt"></i>
                </div>

                <div class="button-area">
                  <button type="submit">Send Message</button>
                  <span>Sending your message...</span>
                </div>

            </form>
        </div>
    </div>
    <script src="js/app1.js"></script>
</body>
</html>

I don't know what is going wrong. Let me know if you need more code to figure out the problem. Thanks in advance!

1 Answers

If it works on your local server, it must be due to a difference in the live server. Check your ContactUs.html file. If this page calls your localhost server, it will not work on the live server. Make sure the live version of your ContactUs.html is calling/submitting to the live server address and not still calling localhost.

EDIT: Thank you for adding the contact page code. On this line you define your form tag:

<form class="contact-form">

If no action attribute is set (e.g. <form class="contact-form" action="http://myserver.com/mypage">), it will submit the form to the current page. If both your local server and contact page are running on //localhost/ then this will work. On the live page, make sure your server and contact page are running on same address and port.

If this does not work, post the error that happens when you try to submit the form.

Related