如何使用Cloud Functions解决Firebase中的“ TypeError:无法读取未定义的属性'firstname'”?

时间:2019-02-15 12:35:31

标签: firebase express google-cloud-firestore google-cloud-functions

我正在尝试使用Cloud Functions在Firestore数据库中创建文档。还使用Postman发送以下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)
    })
})

这是ErrorMessage:

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?

  

更新:   这是我的Web应用程序的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 :(得分:2)

更改此:

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对象为您提供一种将响应发送回给客户端的方法。客户。

express框架的请求对象具有属性body,其中包含提交的数据: http://expressjs.com/en/4x/api.html#req.body

答案 1 :(得分:0)

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