Email responses containing unidentifiable values

Currently, I am working on implementing AJAX for my contact form to send form data to the server. The objective is to have the server email me the user's information extracted from the input fields.

However, I'm encountering an issue where the formData appears to be functioning normally (seen in the browser network tab), but when I receive the email, the values are coming through as undefined.

const submit = document.querySelector('.contact-btn');

submit.addEventListener('click', send);

function send(event){
    event.preventDefault();
    const url = "https://us-central1-selexin-website.cloudfunctions.net/app/sendemail";
    let form = document.querySelector('form');
    let formData = new FormData(form);
    const xhr = new XMLHttpRequest();
    xhr.onreadystatechange = () => {
        if(xhr.readyState === XMLHttpRequest.DONE){
            console.log(formData)
    // Display a green pop-up message below the textarea box notifying the user that the email was sent.

    }   
}
    xhr.open('POST', url, true);
    xhr.send(formData);
};

The following are the fields being emailed to me. As you can observe, I included "run test" within the email body as a string and it shows up perfectly in the email. Why then, is req.body returning undefined values?

const transport = nodemailer.createTransport(sendgridTransport({
    auth: {
        api_key: apiKey
    },
}));

app.use(express.urlencoded({extended: false}));
app.use(cors({ origin: true }));

app.post('/sendemail', (req, res) => {
    const {name, email, number, message} = req.body;
    return transport.sendMail({
        to: 'email receiving', 
        from: 'from this email',
        subject: 'New Contact Request',
        html: `
        <p>You have a new Contact Request</p>
        <h3>Contact Details</h3>
        <ul>
            <li>Name: 'Run test'</li>
            <li>Email: ${email}</li>
            <li>Number: ${number}</li>
            <li>Message: ${message}</li>
        </ul>
        `
    }).then(() => {
        if(res.sendStatus(200)){
            console.log('it logs');
        };
    })
 });

exports.app=functions.https.onRequest(app);

Answer №1

Ensure you are sending your request body as multipart/form-data instead of

application/x-www-form-urlencoded
.

If you need to handle the former, consider implementing the Multer middleware in your Express application.

An easy fix is wrapping your FormData in URLSearchParams.

xhr.send(new URLSearchParams(formData))

By doing this, your data will be posted as

application/x-www-form-urlencoded
, which can be managed by the express.urlencoded() middleware that you are already utilizing.


I also suggest attaching an event listener to your form's submit event rather than a button click. This allows you to capture actions like "press Enter to submit".

document.querySelector("form").addEventListener("submit", e => {
  e.preventDefault()
  const formData = new FormData(e.target)

  // ...and continue with your "send" logic
})

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

Tips for keeping the main section from scrolling while scrolling through the side navigation

Within my Angular application, I have implemented a sidenav and a main section. My desired behavior is to prevent any scrolling in the main section while I am scrolling in the sidenav, similar to the functionality seen on the Angular Material Design docume ...

The attempt to create the property 'and_ff' on the string 'and_chr 89' has failed

Encountering an issue with a Lambda function, I receive an error that does not occur when running the same code within an Express app. I'm puzzled. Data returned by caniuse.getLatestStableBrowsers(); [ 'and_chr 89', 'and_ff 86& ...

What is the best way to eliminate the alert message "autoprefixer: Greetings, time traveler. We are now in the era of CSS without prefixes" in Angular 11?

I am currently working with Angular version 11 and I have encountered a warning message that states: Module Warning (from ./node_modules/postcss-loader/dist/cjs.js): Warning "autoprefixer: Greetings, time traveler. We are now in the era of prefix-le ...

Retrieving data from SQL Server database through Ajax and web service integration in ASP.NET

I attempted to download a specific file from a SQL Server database using Ajax and a web service. The code seems to be executing without any errors, but the file still can't be downloaded. Here is the snippet of the code: My HTML <input id= ...

Creating a Piechart in Kendo UI that is bound to hierarchal remote data

I am facing an issue with binding remote data to a pie chart while managing a grid with dropdown sorting options. The grid is working fine, but I am unable to display the hierarchical data on the pie chart as categories. <!DOCTYPE html> <html> ...

Switch between individual highcharts by selecting or deselecting checkboxes

One of the challenges I am facing involves manipulating multiple scatter plots created with highcharts. I have a list of checkboxes, each labeled to correspond with legend identifiers in the highcharts. My goal is to create a dynamic functionality so tha ...

Conceal or reveal buttons using JavaScript

I am struggling with a function that is supposed to hide certain buttons and create a new button. When I click on the newly created button, it should make the previously hidden buttons visible again. However, the function does not seem to work properly. ...

Executing AJAX requests in an AngularJS application within a Cordova mobile app

After developing an app with Ionic Framework, AngularJS, and Cordova, I encountered a problem with AJAX calls to PHP files. While these calls work flawlessly in a browser, they fail within the app itself. Interestingly, the app is able to render internet p ...

Utilize Google Tag Manager to Safely Gather Specific Data

My current project involves capturing values from a <select> element, sending them to the Data Layer, and then forwarding them to an Analytics account via Google Tag Manager. The source code I'm trying to extract values from includes a dynamic s ...

Here's a guide on using a button to toggle the display of password value in Angular, allowing users to easily hide

I have successfully implemented an Angular Directive to toggle the visibility of password fields in a form. However, I am facing an issue with updating the text displayed on the button based on the state of the input field. Is there a way for me to dynami ...

Ways to pass a class list from a client to a webmethod using AJAX

I have a list of client-side classes in TypeScript that I need to send to a web method. Here is my TypeScript code: class MakeReportData { LocalName: string; FldSi: number; ViewSi:number; TypeName:string ; CheckBoxshow :boolean ; ...

Leveraging JavaScript for Validating Radio Buttons

I've been following a tutorial guide on this specific website , but I'm encountering some difficulties despite following the exact steps outlined. Can someone provide guidance? Here is what I have done: <html> <script> fu ...

Consolidate list: Make sure to leave only the currently active item open

For some reason, I am encountering an issue with this code on this platform. The problem is that every time I click on a list title, all items open up instead of just the one I clicked on. Is there a way to modify this code so that only the clicked item ex ...

Looking to update the key name in a script that produces a list sorted in ascending order

I have been working on code that iterates through a flat json document and organizes the items into a hierarchical structure based on their level and position. Everything is functioning correctly, but I now need to change the name of the child elements to ...

Unable to locate the module '/workspace/mySQL/node_modules/faker/index.js'

Hi there, I'm currently facing an issue while trying to run the app.js file in my project through the terminal. It keeps showing me an error message that I am unable to resolve. To provide some context, I have already installed the faker package using ...

Loop through JSON data using jQuery for parsing

Here is the code snippet I have included below, which is a part of a larger code base: <html> <head> <style> #results{margin-top:100px; width:600px; border:1px solid #000000; background-color:#CCCCCC; min-height:200px;} </style> & ...

A guide to automating POST requests in NodeJS

I'm looking to automate my NodeJS application by sending POST requests every 2 minutes. However, I'm encountering an issue where the console logs are not showing up, and there is no indication that the automation is working. Surprisingly, when I ...

Passing state to getStaticProps in Next JSLearn how to effectively pass state

I am currently fetching games from IGDB database using getStaticProps and it's all working perfectly. However, I now have a new requirement to implement game searching functionality using a text input field and a button. The challenge I'm facing ...

Tips for extracting only a portion of the JavaScript timestamp

I have a JavaScript timestamp that reads Tue Sep 30 2014 12:02:50 GMT-0400 (EDT). When I use the .getTime() method, I get 1412092970.768 Typically, this timestamp represents a specific time of today. My question is whether it's possible to extract o ...

unable to retrieve / interpret data from herdsmen using fetch

When sending a request to a node server, the server responds with headers and a blank body. Despite being able to view the headers in the network activity panel within dev-tools, I faced difficulties reading them using the following code: let uploaded ...