Firebase:TypeError:无法读取未定义的属性(读取‘getIdToken’)
2022-01-22
8529
因此,我在按照 Firebase / React 教程 ( https://www.youtube.com/watch?v=m_u6P5k0vP0&t=2656s ) 进行操作时遇到了一个问题。我在 auth 部分尝试设置新用户,并且成功将新用户带入 firebase 上的 Auth 部分,但我没有取回他们的 id 令牌,因此我无法继续以编程方式创建用户集合。目前,我在命令行上看到 TypeError,并在 Postman 中返回带有空 JSON 字符串的 500 错误。关于我在 data.user.getIdToken() 中遗漏了什么,您有什么想法吗?
const functions = require("firebase-functions");
const admin = require('firebase-admin');
const app = require('express')();
const firebaseConfig = {
apiKey: "***",
authDomain: "***",
databaseURL: "***",
projectId: "***",
storageBucket: "***",
messagingSenderId: "***",
appId: "***",
measurementId: "***"
};
admin.initializeApp(firebaseConfig);
const db = admin.firestore();
// First function is to get all screams (feed posts)
app.get('/screams', (req, res) => {
db
.collection('screams')
.orderBy('createdAt', 'desc')
.get()
.then((data) => {
let screams = [];
data.forEach((doc) => {
screams.push({
screamId: doc.id,
body: doc.data().body,
userHandle: doc.data().userHandle,
createdAt: doc.data().createdAt
});
});
return res.json(screams);
})
.catch((err) => console.error(err))
})
// Second functions is to create ie post new screams from a json format
app.post('/screams', (req, res) => {
const newScream = {
body: req.body.body,
userHandle: req.body.userHandle,
createdAt: new Date().toISOString()
};
db.collection('screams').add(newScream).then((doc) => {
res.json({ message: `document ${doc.id} created successfully` })
})
.catch((err) => {
res.status(500).json({ error: 'something went wrong' });
console.error(err);
})
});
// Signup route
app.post("/signup", (req, res) => {
const newUser = {
email: req.body.email,
password: req.body.password,
confirmPassword: req.body.confirmPassword,
handle: req.body.handle
};
db.doc(`/users/${newUser.handle}`).get()
.then(
doc => {
if(doc.exists){
return res.status(400).json({ handle: 'This handle already taken' });
} else {
return admin
.auth()
.createUser({
email: newUser.email,
password: newUser.password,
})
}
})
.then(data => {
data.user.getIdToken();
})
.then(token => {
return res.status(201).json({ token });
})
.catch((err) => {
console.error(err);
return res.status(500).json({ error: err.code });
});
});
// export api allows us to use express for our function formating
exports.api = functions.https.onRequest(app);
TypeError: Cannot read properties of undefined (reading 'getIdToken')
at /Users/tmac/Desktop/SMTutorial/functions/index.js:84:22
at processTicksAndRejections (node:internal/process/task_queues:96:5)
1个回答
createUser()
方法返回一个
UserRecord
,该记录没有
user
属性。此外,您似乎正在尝试使用 Admin SDK 获取用户的 ID 令牌,而这在本机上是不可能的。请查看
In firebase - 如何在服务器上生成 idToken 以用于测试目的?
以了解更多信息。
在服务器上创建用户后,您只需发回响应,然后使用 Firebase 客户端 SDK 登录用户即可。还可以尝试重构代码,如下所示:
app.post("/signup", async (req, res) => {
const newUser = {
email: req.body.email,
password: req.body.password,
confirmPassword: req.body.confirmPassword,
handle: req.body.handle
};
const userDoc = await db.doc(`/users/${newUser.handle}`).get()
if (userDoc.exists) {
return res.status(400).json({ handle: 'This handle already taken'});
}
// Create user
await admin.auth().createUser({ email: newUser.email, password: newUser.password })
return res.json({ data: "User created" })
})
客户端的流程可以像这样:
- 用户输入凭据并触发“/signup”API
- 服务器返回成功响应后,使用 Firebase 客户端 SDK 使用相同凭据登录用户。
Dharmaraj
2022-01-22