gpt4 book ai didi

javascript - 如何使用 Cloud Functions 在 Firebase 中解决 "TypeError: Cannot read property ' firstname' of undefined"?

转载 作者:行者123 更新时间:2023-11-30 14:09:41 25 4
gpt4 key购买 nike

我正在尝试使用 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)
})
})

这是错误消息:

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 文档中进行了搜索,但没有找到任何内容。如何定义参数“firstname”以避免错误消息?

Update: This is a snippet of the index.js of my web app that is causing the same results as the request with 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)
});
}

最佳答案

改变这个:

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 请求。

根据文档:

Used as arguments for onRequest(), the Request object gives you access to the properties of the HTTP request sent by the client, and the Response object gives you a way to send a response back to the client.

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

关于javascript - 如何使用 Cloud Functions 在 Firebase 中解决 "TypeError: Cannot read property ' firstname' of undefined"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54709540/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com