- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试使用 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()
, theRequest
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/
我是一名优秀的程序员,十分优秀!