What is the solution to the error message "TypeError: Cannot read property 'firstname' of undefined" when working with Firebase and Cloud Functions?

I'm having some trouble creating a new Document in my Firestore database using Cloud Functions. I am also using Postman to send a POST request with the following data:

{
    "firstname": "TestFirst2",
    "lastname": "TestLast2",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a6d2c3d5d294e6d2c3d5d288c5c9cb">[email protected]</a>"
  }
  

This is the Cloud Function I am trying to run:

const functions = require('firebase-functions');
  const admin = require('firebase-admin');
  admin.initializeApp();

  exports.addUserReq = functions.https.onRequest((request, response) => {
    const firstname = String(request.data.firstname)

    const col = admin.firestore().collection(`users`)
    col.add({
        firstname: firstname,
        lastname: request.data.lastname,
        email: request.data.email})
        .then(snapshot => {
        const data = snapshot.data()
        return response.send(data);
      })
      .catch(error => {
        console.log(error)
        response.status(500).send(error)
      })
  })
  

Here is the error message I am encountering:

TypeError: Cannot read property 'firstname' of undefined
  at exports.addUserReq.functions.https.onRequest (/user_code/index.js:14:34)
  at cloudFunction (/user_code/node_modules/firebase-functions/lib/providers/https.js:57:9)
  at /var/tmp/worker/worker.js:735:7
  at /var/tmp/worker/worker.js:718:11
  at _combinedTickCallback (internal/process/next_tick.js:73:7)
  at process._tickDomainCallback (internal/process/next_tick.js:128:9)
  

I have already checked the Firebase documentation, but couldn't find a solution. How can I prevent this error from occurring when trying to define the "firstname" parameter?

Update: This is a snippet of the index.js file in my web application that is encountering the same issue as the Postman request.

function save() {

    var userFirstname = document.getElementById("firstname_field").value;
    var userLastname = document.getElementById("lastname_field").value;
    var userEmail = firebase.auth().currentUser.email_id;

    var addUser = functions.httpsCallable('addUserReq');
    addUser({
      "users": {
          "firstname": userFirstname,
          "lastname": userLastname,
          "email": userEmail
        }
      }
      ).then(function(result) {
      var result = result;
    }).catch((err) => {
      alert(err)
    });
  }
  

Answer №1

Modify the following code:

exports.addUserReq = functions.https.onRequest((request, response) => {
const firstname = String(request.data.firstname)

to this:

exports.addUserReq = functions.https.onRequest((request, response) => {
const firstname = String(request.body.firstname)

Firebase utilizes the express framework for handling http requests.

As per the documentation:

When used as arguments for onRequest(), the Request object provides access to the properties of the HTTP request sent by the client, while the Response object allows sending a response back to the client.

The express framework's request object includes the body property that contains the submitted data: http://expressjs.com/en/4x/api.html#req.body

Answer №2

     col.add({
      // What is the source of this 'firstname' variable?,
firstname: request.data.firstname,
lastname: request.data.lastname,
       email: request.data.email})
       .then(snapshot => {
       const data = snapshot.data()
       return response.send(data);
    })
    .catch(error => {
       console.log(error)
       response.status(500).send(error)
    })

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

Invoke a different route within Express Router when it needs to display a Not Found error (404)

Hey there, how are you? Below is the code I've been working on: const router = Router(); router.use( `${routePrefix}/v1/associate-auth/`, associateAuthRoutesV1(router) ); router.use( `${routePrefix}/v1/associate/`, JWTVerify, ...

The latest version of Material UI, v4, does not currently support React 18

Looking to incorporate MUI (Material UI) into my website design. Encountering difficulties with installing this library, receiving the error message below: -npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While ...

Top method for utilizing overlays

Is there a method to randomly select hex codes for specific colors? I want to replicate the design in this image through coding. Image Here is the code I have so far: HTML <div id="group"> <div class="sub red panel"> </div><!--su ...

Using JQuery to handle click events on an array of checkboxes and displaying the value of the selected

I am struggling to show the label text and checkbox value from a checkbox array whenever each one is clicked (for testing purposes, assume I want it to appear in an alert). My HTML looks like this: <label class="checkbox"> <input type="checkbox" ...

What is the process for transferring an image from an iOS App to node.js?

Looking for assistance with iOS Code, specifically uploading an image from an iPad app to a Node.js server using multiparty. I found a helpful thread on Stack Overflow. The server is running on Node.js and express, and the upload.js path is located in ./r ...

Invalid content detected in React child element - specifically, a [object Promise] was found. This issue has been identified in next js

Why am I encountering an error when I convert my page into an async function? Everything runs smoothly when it's not an async function. The only change is that it returns a pending object, which is not the desired outcome. This is how data is being f ...

Loading images lazily using knockout.js

I have been working on implementing lazy loading for images using knockoutjs binding. I previously successfully implemented lazy loading without the knockoutjs framework, but I am unsure of how to achieve this with knockoutjs binding. Below is my HTML code ...

Using JQuery, ensure that the scroll function runs in advance of the ajax call finishing

I am currently working on using jQuery to scroll down to a text box when the click event occurs. However, I have noticed that the scroll event is happening after the AJAX call within the function. $("#execute_btn").click(function(){ $('html, b ...

My Fullcalendar is displaying events for the upcoming month. How can I resolve this issue?

This is the start date for my event in the full calendar: start: new Date('2016', '02', '07', 00, 30) However, when loading the calendar, this event is displaying on March 7, 2016. How can I resolve this issue? ...

Trouble with transmitting props to function

The child component is not receiving the props as expected. When printed, it displays an empty object. The problem seems to be in the News.js file specifically related to passing props to the child component from App.js. All functions are operational excep ...

Angular: Issue with FormArrays not iterating properly

Apologies for the lengthy post, but I needed to provide a detailed explanation of the issue I am facing. In my form, there is a control that contains an array of JSON data. I have created a reactive form based on this structure. Below are the JSON data an ...

vue.js: Modifying information through watcher function

Here is the code I am currently using: export default { name: '...', props: ['user'], data() { return { userName: this.user.name } }, watch: { user: (_user) => { th ...

What is the best way to adjust the size of an image as I navigate down a webpage?

I've been working on designing a navigation bar for a website, but I'm running into some issues. My goal is to have the logo shrink as the user scrolls down the site. I've experimented with webkit animations and various javascript/jQuery fun ...

Adjusting the Stripe Button to Utilize a Unique Button Class

I have a stripe button on my website and I want to add my custom class to it. I discovered that manually creating the CSS for it can work, but I prefer to maintain consistency across all buttons on my site by using my custom class. No matter what I attemp ...

What could be causing my jQuery switch not to function on the second page of a table in my Laravel project?

Having an issue with a button that is supposed to change the status value of a db column. It seems to only work for the first 10 rows in the table and stops functioning on the 2nd page. I'm new and could really use some help with this. Here's the ...

Failed to locate lodash during npm installation

I recently set up my project by installing lodash and a few other libraries using npm: npm install grunt-contrib-jshint --save-dev npm install grunt-contrib-testem --save-dev npm install sinon --save-dev npm install -g phantomjs npm install lodash --save ...

The carousel's slides don't behave properly when swiping or using the slider controls (next/prev)

I have recently completed the construction of a carousel with swipe/touch functionality and control buttons for previous and next slides. However, I am facing an issue with the behavior of the carousel as it seems to be sliding by 2 or 3 instead of one at ...

Identifying the floor or ground using a webcam in motion: A step-by-step guide

I am currently facing a unique challenge: In my project, I have markers (specifically Hiro, A, Kanji) displayed on banners, and I need to show a 3D model (such as augmented reality) when the marker is recognized. Everything works well so far, but here&apo ...

Looking to display several charts on a single page with varying datasets?

I have successfully integrated a doughnut chart plugin into my website. However, I would like to display multiple charts on the same page with different data sets. Below is the code snippet for the current chart being used: This is the chart I am using & ...

Is React capable of storing and recognizing images within its system?

As a junior developer, I find this aspect confusing. Specifically, does reusing the same image on multiple routes in React result in the user downloading it more than once in the browser? I am striving to understand whether using the same image repeatedly ...