类型“User”上不存在属性“accessToken”&& firebase 未定义

问题描述 投票:0回答:3

我在 React 应用程序中使用 TypeScript,但在获取用户的 accessToken 时出现错误

“属性 'accessToken' 在类型 'User' 上不存在”

我的组件中的处理函数:

const handleRegister = (email: string, password: string) => { const auth = getAuth(); createUserWithEmailAndPassword(auth, email, password) .then(({user}) => { dispatch(setUser({ email: user.email, token: user.accessToken, id: user.uid })); }); }
在寻找这个问题的解决方案后,我这样做了

token: (user as unknown as OAuthCredential).accessToken,
IDE 会自动添加以下导入

import firebase from "firebase/compat"; import OAuthCredential = firebase.auth.OAuthCredential;
但是之后我在控制台中收到错误

“未捕获的引用错误:firebase 未定义”。 我觉得自己很蠢,但不明白如何解决

reactjs typescript firebase firebase-authentication
3个回答
0
投票
这样做看看你会得到什么结果,我认为你需要 result.user.accessToken 但我不确定

signInWithEmailAndPassword(auth, email, password) .then((result: any) => { // Signed in console.log(result) // ... })
    

0
投票
我还没有测试过这个,但你可以使用如下所示的东西。

const handleRegister = (email: string, password: string) => { const auth = getAuth(); createUserWithEmailAndPassword(auth, email, password) .then(({user}) => { user.getIdToken().then(function(idToken) { // Send token to your backend via HTTPS dispatch(setUser({ email: user.email, token: idToken, id: user.uid })); // ... }).catch(function(error) { // Handle error }); }); }
    

0
投票
我发现当从api获取响应时,response.user.getIdToken()返回一个promise。你可以等待它。像这样的东西:

signInWithEmailAndPassword(auth, email, password) .then(async (response) => { const token = await response.user.getIdToken(); console.log(token); redirect("/"); })
我希望这有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.