Having difficulty retrieving data from function call sent to Firebase cloud functions

One of my Firebase functions is named sendMail and it is responsible for sending emails. I am facing an issue while trying to pass the email address of the recipient along with another parameter to this function. Within my Vue application, I invoke the function in the following manner:

sendEmail(){
            console.log(this.email)
            let sendMail = firebase.functions().httpsCallable('sendMail');
            sendMail(
                {
                    "email": this.email,
                    "superu": this.superu
                }
            ).then(
                result => {
                    console.log(result)
                }
            )
        }

The contents of my index.js function script are as follows:

const functions = require('firebase-functions');
const admin = require("firebase-admin")
const nodemailer = require('nodemailer');

admin.initializeApp()

var transporter = nodemailer.createTransport({
    host: 'smtp.gmail.com',
    port: 465,
    secure: true,
    auth: {
        user: '*****@****.com',
        pass: '***********'
    }
});


exports.sendMail = functions.https.onRequest((req, res) => {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Content-Type");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");        

    console.log(req.body['data']);
    const mailOptions = {
        from: `•••••••••@gmail.com`,
        to: req.body['data'].email,
        subject: 'contact form message',
        html: `<h2 style="color: teal">Order Confirmation</h2>
                            <a href="https://track-acquintances.firebaseapp.com/signup/${req.body.superu}">
                               <b> Register </b>"<br>
                            </a>`
    };


    return transporter.sendMail(mailOptions, (error, data) => {
        if (error) {
            return res.status(200).json({data: error.message});
        }
        data = JSON.stringify(data)
        return res.status(200).json({data: data});
    });

});

I have been unable to access the passed email data which is causing the function to fail. Upon logging req.body['data'] in the functions logs, it displays

{ email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f48c8c8cb48c8cda8c8c8cda8c">[email protected]</a>', superu: true }
. Despite attempting both req.body['data'].email and req.body['data']['email'], neither seem to work. Additionally, my browser's console outputs {data: "No recipients defined"}. I would greatly appreciate any assistance. Thank you.

Answer №1

There seems to be some confusion regarding the different types of Cloud Functions:

  • The Cloud Function in question is an HTTPS triggered function, designed to be invoked by accessing its URL through a browser, using fetch, or via XMLHTTPRequest.

  • However, the client code appears to be trying to invoke a Callable Cloud Function, which operates differently. Callable Cloud Functions are also accessed over HTTPS but have a specific protocol for invocation.

Due to this mismatch, the parameters are being passed in a format that is not compatible with how the server expects them.

To resolve this issue, you can either stick to calling the HTTPS function as intended or make necessary changes to convert the Cloud Function into a Callable version. Here's an example of how it could look like:

exports.sendMail = functions.https.onCall((data, context) => {
  const email = data.email;
  const superu = data.superu;

  ...
});

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

The event object is not defined in the dojo.connect function

Following Dojo's documentation, I linked a function using dojo.connect to a dojox.layout.ContentPane: dojo.connect(cp, 'onHide', function(e) { alert('test'); console.log(e); }); My assumption was that argument e would con ...

Extracting data from a Wikipedia table using web scraping in JavaScript

I'm attempting to extract information from a specific website. <script> var convertToInt; var allData = []; $.ajax({ url: "http://en.wikipedia.org/wiki/Demographics_of_Europe", type: 'GET', cache: false, success: func ...

Efficiently Managing and Recording Complex JavaScript Projects Across Multiple Files

Embarking on a sizable JavaScript project, I've decided to organize everything within one or more namespaces to limit the use of global scope. Currently, only one element exists in the global scope. To maintain organization, I prefer keeping each cla ...

Display of div content when hovering over table

I am currently developing a simple interactive calendar, and I need some guidance on how to make it more dynamic. Initially, I want only the months to display, but upon hovering over a month, I would like all the individual days to appear. Eventually, user ...

Enclose the string stored in the variable with double quotation marks

I am retrieving a variable called audioUrl from the database which is stored as a string url. The issue I am facing is that the url does not have double quotes around it, so I need to add them manually. Below is my code snippet: var audioUrl; // The ur ...

What is the reason behind the lack of output in Javascript .filter() when using an active filter (== or ===) compared to the successful operation with the boolean logic type of != or !==?

import React from "react"; import productsData from "./products.js"; import Product from "./Product.js"; function App() { const importedProductsArray = productsData.map((item) => ( <Product id={item.id} ...

What is the best way to design a grid with various squares in React Native?

Here's the design I aim to achieve: I am looking to implement the above layout in react native and ensure it is responsive on all screen sizes. I attempted using flexbox but couldn't figure out how to make the boxes square shaped. The code provi ...

Transferring documents using JavaScript

I have been using the following method to upload files to my Laravel backend: setFile(id, e) { let self = this; let reader = new FileReader(); reader.readAsDataURL(e.target.files[0]); reader. ...

What is the best way to loop through an object and show each item in its own row?

My goal is to loop through an object where each item has a type property. The objective is to iterate through the objects and display them in rows based on their type. Currently, it looks like this: https://i.sstatic.net/8iTtG.png I aim to have Frontend, ...

Utilizing the combineReducers() function yields disparate runtime outcomes compared to using a single reducer

Trying to set up a basic store using a root reducer and initial state. The root reducer is as follows: import Entity from "../api/Entity"; import { UPDATE_GROUPING } from "../constants/action-types"; import IAction from "../interfaces/IAction"; import IS ...

Incorporating an Array into a JSON Object and transmitting it to a server

I have stored an Object in a .json file that contains only an Array. Now I want to prompt the user for a word and add it to this Array. Below are the relevant code snippets: function addWord() { let myWords = getWords(); let newWord = prompt("Ple ...

Utilizing $asyncValidators in angularjs to implement error messages in the HTML: A guide

This is my first major form with validations and more. I've set up a Registration form and I'm utilizing ng-messages for validation. The issue arises when I have to check the username, whether it already exists in the JSON server we are using or ...

There seems to be an issue with this forEach loop as it is not functioning correctly

let wordsToRemove = ['extremely', 'literally', 'actually']; textWords = text.split(' ') let refinedWords = textWords.filter(function (word) { return !wordsToRemove.includes(word) }) let reallyCount = 0 let basic ...

Tips for adjusting the font size according to the varying number of characters entered

I am currently facing a challenge with adjusting the font size based on the dynamic number of characters. For example, I have a set of characters with a font-size of 40px, and as more characters are added, the font size should decrease to fit within the av ...

troubleshoot using Visual Studio Code

Here's the scenario: I need to debug a project using VS Code. The project is usually started by a batch file and then runs some JavaScript code. Now, I want to debug the JavaScript code, but I'm not sure how to do that. If anyone has any instruct ...

When I attempt to make a incorrect POST request, my app does not return the expected err property and instead crashes

User.findOne({ email }, (err, user) => { if(err){ console.log(err); return res.status(400).json({ message: "USER does not exist" }) } if (!user.authenticate(password)){ return res.stat ...

How Can You Update the State of a Parent Component from a Child Component?

My Objective In the initial component, I retrieve items with a status of 2 and display them as checkboxes. In the subsequent component, I update the status of these items to 3. In the third component, a modal opens after the status change from the secon ...

Safari 15.6.1 does not support background video playback in Next.js

Currently using Safari version 15.6.1 for a small website project, I have encountered an issue where the video appears frozen with an arrow in the middle. Oddly enough, this problem only occurs on Safari as both Chrome and Firefox display the code correctl ...

What is the best method to utilize a promise to delay the execution of a function until the data is received and stored

Currently, I am facing an issue with my API where the model variable is returning undefined before any data is populated in the return_array. I am unsure of how to implement promises or another method to ensure that the variable waits for data to be fille ...

Iterate through each item using jQuery's each() method and process them one at a time after the

Can someone help me with this code? $("[input]").each(function(){ var data = $(this).val(); $.post('someurl.php',{data:data},function(result){ alert(result); }); }); I've noticed that when I check the network tab, the ajax reques ...