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

Invoker of middleware and stack functions for Express.js with a focus on capturing the response object

It appears that the expressjs app contains a stack of Layer object Arrays. What function is utilized to pass the I am curious about: When a request is sent from the http client, which function is called first and how are the stack array functions with mi ...

"Take your nodejs jade templates to a global level with international

I'm working on internationalizing my nodejs express app with the i18n-2 module. Everything is functioning correctly, but I have a question about translating strings in my jade templates. If I have a large number of strings on my website, do I need to ...

Troubleshooting the issues with implementing cross-browser jscrollpane functionality

Hey there! I've been exploring this tool to customize the default scroll-bar, and here's a fiddle showcasing my experimentation. In the fiddle, I've included the following code snippet <div class="scroll-pane horizontal-only">(located ...

Show drawer when modal is open in React Native

Currently, I am working on a project in react-native and facing an issue where the modal is appearing over the drawer navigator. Despite trying to adjust the zIndex property, it has not been effective. Details of my modal: <Modal visible={isVisible} ...

`Only when an error is thrown will the express session be updated`

I am encountering an issue with storing and updating a single variable on a sessionCookie. Strangely, the session object only gets updated if I deliberately trigger an error immediately after setting the value. When following the documented approach, the v ...

Creating custom paths by using Express Route Parameters may lead to the generation of

Currently, I am in the process of developing a to-do list application and facing some challenges while incorporating custom routes utilizing 'Express Route Parameters'. Everything was functioning smoothly until I attempted to implement these cust ...

Retrieve information in JSON format using AngularJS by fetching data from SQL through PHP

My objective is to retrieve data from a mySql database using PHP, convert it to JSON, and then display it through AngularJS. Although I have successfully completed the steps leading up to this point, I am facing issues with the final step. Below are the de ...

What led to the decision for the two distinct chart elements to merge into a single container?

In the process of creating a dashboard using React.js and d3.js, I encountered an interesting issue that perplexed me for quite some time. Below is the Scatterplot.js code written in d3.js: import React, { Component } from "react" import * as d3 from "d3 ...

What is the best way to retrieve the second to last element in a list

When using Protractor, you have convenient methods like .first() and .last() on the ElementArrayFinder: var elements = element.all(by.css(".myclass")); elements.last(); elements.first(); But what about retrieving the element that comes right before the ...

Anchor tags created using JQuery will remain on the same page without redirecting

Presented below is the code I have utilized to construct the anchor tag along with its content. $('div#right-slide').html("<a href=\"http://www.XXXXXXXXXXXX.info/limited-specials/\" ><h1 id=\"specials\">Click Here ...

Does JavaScript automatically round large numbers?

I have a simple array: myArray = [{"egn":79090114464},{"egn":92122244001},{"egn":10005870397643185154},{"egn":10000330397652279629},{"egn":10000330397652279660},] However, when I append the values from thi ...

Is there a way to resolve issues with window.open() on Heroku platform?

I've been working on hosting a webpage on Heroku using Node.js. Instead of using the php method, I opted to go with Node and it's been going smoothly so far. However, I've run into a small issue. Here's what my Procfile looks like: web ...

Tips for specifying the "url" parameter in xmlhttp.open() for utilizing Ajax in communication with node.js

server.js has the ability to generate a random number. I am trying to retrieve a random number from the server and utilize xmlhttp to send a request. However, the string value remains unchanged when I visit http://localhost:3000/index.html. What could be c ...

Employing jQuery to populate information into an input field, yet encountering an issue where the data is not being successfully transmitted to

On my page, there is a form with an input box <input name="bid_price" id="bid_price" class="form-control"> If I manually enter a value, it gets posted successfully But when I try to insert a value using jQuery, it doesn't get posted, even tho ...

Tips for clearing all content within a React Material UI table

How can I create a reset button to clear a table filled with user input data, without having to write functions from scratch? For example, similar to using clearLayer() for clearing a leaflet map. Thank you for any suggestions! //example of dynamical ...

What is the best way to eliminate properties from objects stored in a MongoDB array?

Below are some code snippets to help clarify my question. Currently, I am able to fetch an object that contains an array of category objects. However, I only want to display specific properties from these category objects. This is the current output: { ...

Leveraging the power of $.ajax within the Kendoui datasource for the Grid

I am currently attempting to utilize a jquery ajax call for updating the datasource in my kendoui Grid. Below is the sample code that I found in the documentation: update: function(options) { // make JSONP request to http://demos.telerik.com/kendo ...

Issue with Material UI select component not displaying the label text

I've been struggling with Material UI's "Select" for quite some time now - spent about 10 hours trying to make it work the way I want. Any help would be greatly appreciated. This question is connected to a previous one: Select MenuItem doesn' ...

Could it be that the function is returning undefined because console.log is executing before the result is actually returned? Perhaps a promise

There is a function located in another file that I need to extract the response from and perform an action based on that response before completing my controller function. This is the snippet of code from the external file: exports.counter = function(com ...

HTML dropdown menu to trigger an action with the submitted URL

I need assistance creating a menu of options with corresponding URL actions. Here is the structure I have in mind: <form> <select> <option value="1">1</option> <option value="2">2</option> <option value="3 ...