Please furnish request.body with all necessary details for nodemailer, excluding the email address

I'm currently working on a contact form for my node.js and express web app, utilizing nodemailer.

Everything seems to be functioning correctly - the server is recording information and sending it to the specified email address. However, there is an issue regarding the email section in the message, which appears as "--- email: ''." It's not causing errors but remains blank.

In addition, this "email: ''" text shows up on the server side, but it isn't displayed in the email sent by the function at all.

I've attempted to adjust the html body section and troubleshoot any potential issues with the form or the javascript, but haven't found a solution yet.

Any assistance would be greatly appreciated! Thank you!

The structure of app.js is outlined below:

//jshint eversion:6

const http = require('http')
const express = require("express");
const bodyParser = require("body-parser")

const ejs = require('ejs');
const nodemailer = require('nodemailer');
const hostname = '127.0.0.1';
const path = require('path');
const port = 3000;


const app = express();


app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({
    extended: false
}));
app.use(express.json());



// custom middleware to log data access
const log = function (request, response, next) {
    console.log(`${new Date()}: ${request.protocol}://${request.get('host')}${request.originalUrl}`);
    console.log(request.body); // make sure JSON middleware is loaded first
    next();
}
app.use(log);
// end custom middleware


app.use(express.static('public'));
app.use(express.static('images'));



app.get("/", function (req, res) {
    res.render("index");
});

app.get("/prices", function (req, res, ) {
    res.render("prices");
});

app.get("/about", function (req, res, ) {
    res.render("about");
});
app.get("/contact", function (req, res, ) {
    res.render("contact");
});

module.exports = function () {
    this.Categories = require('tools.js');
}



// HTTP POST
app.post("/ajax/email", function (request, response) {
    // create reusable transporter object using the default SMTP transport
    const transporter = nodemailer.createTransport({
        host: "smtp.gmail.com",
        port: 465,
        secure: true,
        auth: {
            user: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="85ddddddddddddddddc5e2e8e4ece9abe6eae8">[email protected]</a>", // this should be YOUR GMAIL account
            pass: "XXXXXX" // this should be your password
        }
    });

    var textBody = `FROM: ${request.body.fname}  EMAIL: ${request.body.email} MESSAGE: ${request.body.comment}`;
    var htmlBody = `<h2>Mail From Contact Form</h2> <p>from: ${request.body.fname} ${request.body.lname} </p> <p>${request.body.email}</p>  <p>${request.body.phone}</p> <p>${request.body.company}</p><p>${request.body.comment}</p>`;
    var mail = {
        from: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b7f3d2dbc3d6f3d2c4ded0d9c4f0dbd8d5d6dbf7d0dad6dedb99d4d8da">[email protected]</a>", // sender address
        to: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1c767d71796f327d326a7d727879727e796e7b5c7b717d7570327f7371">[email protected]</a>", // list of receivers (THIS COULD BE A DIFFERENT ADDRESS or ADDRESSES SEPARATED BY COMMAS)
        subject: "Mail From Contact Form", // Subject line
        text: textBody,
        html: htmlBody
    };

    // send mail with defined transport object
    transporter.sendMail(mail, function (err, info) {
        if (err) {
            console.log(err);
            response.json({
                message: "message not sent: an error occurred; check the server's console log"
            });
        } else {
            response.json({
                message: `Thanks for reaching out! We'll contact you ASAP`
            });
        }
    });
});


const PORT = process.env || port;


// const server = http.createServer((req, res) => {
//     res.statusCode = 200;
//     res.setHeader('Content-Type', 'text/plain');
//     res.end('Hello World! NodeJS \n');
// });

app.listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`);
});

The structure of the form and Java script is as follows:

 <div class="contact-form" id="contact-id">
          <form action="/ajax/email" class="contact-form" method="POST" onsubmit="return submitEmailForm(this);">
          <div class="form-group">
            <label class="control-label col-sm-2" for="fname">First Name:</label>
            <div class="col-sm-10">
              <input type="text" class="form-control" id="fname" placeholder="Enter First Name" name="fname">
            </div>
          </div>
          <div class="form-group">
            <label class="control-label col-sm-2" for="lname">Last Name:</label>
            <div class="col-sm-10">
              <input type="text" class="form-control" id="lname" placeholder="Enter Last Name" name="lname">
            </div>
          </div>
          <div class="form-group">
            <label class="control-label col-sm-2" for="email">Email:</label>
            <div class="col-sm-10">
              <input type="email" class="form-control" id="email" placeholder="Enter Email" name="email">
            </div>
          </div>
          <div class="form-group">
            <label class="control-label col-sm-2" for="phone">Phone:</label>
            <div class="col-sm-10">
              <input type="tel" class="form-control" id="phone" placeholder="Enter Phone Number" name="email">
            </div>
          </div>
          <div class="form-group">
            <label class="control-label col-sm-2" for="company">Company:</label>
            <div class="col-sm-10">
              <input type="text" class="form-control" id="company" placeholder="Enter Company Name" name="email">
            </div>
          </div>
          <div class="form-group">
            <label class="control-label col-sm-2" for="comment">Question:</label>
            <div class="col-sm-10">
              <textarea class="form-control" rows="5" id="comment">What services are you interested in?</textarea>
            </div>
          </div>
          <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
              <button type="submit" class="btn btn-default">Submit</button>
            </div>

          </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</section>
<!-- <hr>
<div class="contactQuote">
  <h1>Coming together is a beginning, <br>
    staying together is progress, <br>
    & working together is success.
  </h1>
</div>
<hr> -->
<!-- <div col-12 class="contactCollabImg">
  <img class="contactImg2" src="images/contactcollabImg.jpg" alt="" srcset="">
</div> -->

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
  function submitEmailForm(form) {
    var obj = new XMLHttpRequest();
    obj.onreadystatechange = function(){
      if(obj.readyState == 4){
        if(obj.status == 200){
          var res = JSON.parse(obj.responseText);
          alert(res.message); 
        }
        else{
          alert("XMLHttp status " + obj.status + ":Failed to Send Message " + obj.statusText);
        }
      }
    };
    obj.open("post", form.action, true);
    obj.setRequestHeader("Content-Type", "application/json"); // NOTICE: "application/json"
    obj.send(JSON.stringify({ fname: form.fname.value, lname: form.lname.value, email: form.email.value, phone: form.phone.value, company: form.company.value, comment: form.comment.value }));
    return false;
  }
</script>

Answer №1

Eureka! The solution finally dawned on me. It turns out that I had simply overlooked changing the 'name' field to their respective id on a few form elements after copying and pasting them while writing.

And just like that, the issue was resolved!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Form featuring many submission buttons

Can anyone help me identify which submit button has been clicked on a form with multiple buttons? $("#my_form").on("submit", function(event) { event.preventDefault(); var form_action = $(this).attr("action"); var form_data = $(this).seri ...

There seems to be an issue with the hidden field value not being properly set within the

I created a function called getConvertionValue. Inside this function, I make an ajax call to the getCurrencyConvertion function in the controller. function getConvertionValue(from, to) { if (from != to) { $.ajax({ url: base_url + 'admin/o ...

Looking for a foolproof method to determine if a string contains any of the elements in a given array of substrings? And if found, how

I am currently faced with the task of decoding multiple URLs, specifically focusing on encoded special characters like "+", "|", and more. My approach involves having a collection of encoded characters that I need to locate in the URL string. What is the ...

Gap in footer spacing on Internet Explorer is significantly large

The layout of the page is split into two main sections: A large header that takes up 100% of the browser height The main content area and footer When viewing the page in a browser, only one of these sections will be visible. The following code works wel ...

What is the best way to display an alert box through AJAX technology?

My code snippet is as follows: <script> function updateQty(quantity) { $.ajax({ alert(quantity); }) } </script> Here is the corresponding HTML markup: <form name="quantityForm"> <select name="quantity" id="quantity" onChan ...

Having trouble capturing screenshots with PuppeteerJS?

I've encountered an issue while working with Puppeteer to capture screenshots from a provided URL. The code I have below doesn't seem to be functioning properly. It keeps showing the error message: [0] Error: Protocol error (Emulation.setDeviceM ...

How can you retrieve user data using a hook in FeatherJS?

Recently, I started exploring FeatherJS and successfully registered a new user, obtained a token, and accessed protected data by including Authorization in the header. It is important to note that I am exclusively using HTTP Rest API. The documentation fr ...

Ensuring Form Submission is Successful: A Guide to JQuery/Ajax Form Validation and the Importance of Validating Forms and Ajax Operations

I’m currently facing an issue with the form validator I'm using and need help resolving it. The form validator in question can be found at http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/. My problem ...

The JQuery Ajax function is being triggered twice, with the first call successfully executing while the second call is experiencing

Platform: spring I am encountering an issue with my ajax calls in the context of a blur function versus a click function. Oddly enough, the blur function is functioning correctly while the click function is not. Upon changing the name of the function being ...

What are the best methods for ensuring JSON compatibility with Internet Explorer versions 7 and 8?

After implementing jQuery on my website, I encountered issues with Internet Explorer. Despite numerous attempts to fix it, I discovered that the problem lies with JSON not functioning properly in IE. I tried inserting the following code snippet, but it sti ...

Limit DerbyJS to re-rendering specific DOM elements

Currently, DerbyJS (visit http://derbyjs.com) functions by replacing everything in the body tag of the document each time a link is clicked. Is there a way to utilize the template, but replace only the content inside #main-content instead of refreshing th ...

The unhandled type error rises with each scroll I make

Having been diligently working on my current website project, I encountered a puzzling issue. Upon writing code to implement smooth scrolling throughout the site, I found myself facing a persistent error that continues to escalate with each scroll up or do ...

Using React along with Redux to add an object to a nested array

How can I add a new message to an array of connections from a reducer? I have tried finding the right connection by index and then pushing it, but it's not working. The connections schema looks like this: _id: 3213213, messages:[...] The messages sc ...

stuck with an outdated dependency causing issues with create-react-app

Encountering a problem with create-react-app failing due to react-scripts expecting an older version of a dependency, making it difficult to select the new version as suggested. This appears to be an interface issue. Interestingly, I can successfully inst ...

Is there a way to extract just the JSON data from res?

While creating a search functionality to display a list of users, I encountered an error when attempting to load additional pages to show more users: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data var result = JSON.pars ...

Utilizing HTML5 audio elements with jQuery enhances the auditory experience

As I delve into creating a simple media section for a website, I have encountered some challenges that I would like to address. Let me explain the issue I am facing. I currently have a 'play list' consisting of 'links' - represented by ...

Retrieve the values by accessing an element upon clicking the "Submit" button

Here is an interesting example that I found on this website I am currently working on a simple webpage to display both the current forecast and extended forecast. This is my Index.html: <!DOCTYPE html> <!-- To change this license header, choose ...

Eliminate any unnecessary or hidden spacing on the left side of the options within an HTML select

Currently, I am in the process of creating a Registration Form and encountering a challenge with aligning the input[type="text"] placeholder and the "pseudo" placeholder for a <select> element. My goal is to have both placeholders left-aligned flush ...

Unable to connect beyond the local network using Socket.io

server.js import { Server } from "socket.io"; const io = new Server(8000); io.on("connect", (socket) => { console.log(`connect ${socket.id}`); socket.on("ping", (cb) => { console.log("ping"); ...

Revoking Access Tokens in the DocuSign API

I am currently exploring the eSignature API offered by DocuSign. I am testing out their 0Auth system using a demo account (). In some 0Auth setups, when requesting a new accessToken for a user, the previous token may become invalid. However, with DocuSign ...