Как решить «TypeError: Невозможно прочитать свойство 'namename of undefined” в Firebase с облачными функциями? - PullRequest
0 голосов
/ 15 февраля 2019

Я пытаюсь создать документ в моей базе данных Firestore с помощью облачных функций.Также с помощью Почтальона отправлять следующие сообщения POST:

{
"firstname": "TestFirst2",
"lastname ": "TestLast2",
"email": "test2@test.com"`enter code here`
}

Это функция, которую я пытаюсь выполнить:

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)
    })
})

И это сообщение об ошибке:

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)

Я уже искал в документации по Firebase, но ничего не нашел.Как я могу определить параметр «имя», чтобы избежать errorMessage?

Обновление: это фрагмент файла index.js моего веб-приложения, который приводит к тем же результатам, что и запрос к Postman.

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)
 });
}

Ответы [ 2 ]

0 голосов
/ 15 февраля 2019

Измените это:

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

на это:

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

Firebase использует инфраструктуру express для выполнения запросов http.

СогласноДокументы:

Используется в качестве аргументов для onRequest(), объект Request предоставляет вам доступ к свойствам HTTP-запроса, отправленного клиентом, и объекта Response.дает возможность отправить ответ обратно клиенту.

Объект запроса экспресс-инфраструктуры имеет свойство body, которое содержит отправленные данные: http://expressjs.com/en/4x/api.html#req.body

0 голосов
/ 15 февраля 2019
     col.add({
      // firstname: firstname, ==> where is this firstname comming from?,
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)
    })
...