使用Firebase v9发送验证电子邮件

3

我在使用Firebase身份认证模块发送验证邮件时遇到了问题。在以前的Firebase版本中,我是这样做的:

 await firebase.auth().createUserWithEmailAndPassword(data.email, data.password);

 await firebase.auth().currentUser?.sendEmailVerification();

随着Firebase的新版本,我需要像这样做:

import { getAuth, createUserWithEmailAndPassword, sendEmailVerification } from 'firebase/auth';
...
const auth = getAuth();

await createUserWithEmailAndPassword(auth, email, password);

await sendEmailVerification()

问题在于Typescript强制我传递一个类型为User的参数来发送电子邮件验证,但我不知道应该从哪里获取这个用户参数。我尝试从createUserWithEmailAndPassword返回一些内容,但Typescript说它的类型是错误的。所以我的问题是如何获得这个用户对象?
3个回答

6

您需要传递在auth内存在的currentUser,可以使用以下类似内容:

import { getAuth, createUserWithEmailAndPassword, sendEmailVerification } from 'firebase/auth';
...
const auth = getAuth();

await createUserWithEmailAndPassword(auth, email, password);

await sendEmailVerification(auth.currentUser)

2
使用Firebase v9发送验证电子邮件,您可以使用`sendEmailVerification()`方法。
您只需使用以下代码即可。它将在用户创建帐户后向用户发送验证电子邮件。
注意:使用下面的代码时,auth、email和password假定它们不是undefined。
await createUserWithEmailAndPassword(auth, email, password)
  .then((cred) => await sendEmailVerification(cred.user));

在运行上面的代码后(使用createUserWithEmailAndPassword方法),它应该向用户发送一封验证电子邮件。
有关发送电子邮件验证的更多信息,请访问官方Firebase v9文档

0
await createUserWithEmailAndPassword(auth, email, password).then((cred) => await sendEmailVerification(cred.user))

await createUserWithEmailAndPassword(auth, email, password).then((cred) => await sendEmailVerification(cred))

这两个都应该可以工作。


我不会混合使用await和promise chaining。 - Dan Zuzevich

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接